diff --git a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs
index 9286ecd..faad068 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResult.g.cs
@@ -218,6 +218,10 @@ partial void ProcessFetchAudioResultResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs
new file mode 100644
index 0000000..002566a
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.AudioResultsClient.FetchAudioResultAsBytes.g.cs
@@ -0,0 +1,1150 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class AudioResultsClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_FetchAudioResultAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_FetchAudioResultAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_FetchAudioResultAsBytesSecurityRequirement0,
+ };
+ partial void PrepareFetchAudioResultAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string id,
+ ref global::StabilityAI.FetchAudioResultAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion);
+ partial void PrepareFetchAudioResultAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string id,
+ global::StabilityAI.FetchAudioResultAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion);
+ partial void ProcessFetchAudioResultAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessFetchAudioResultAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete.
+ ///
+ ///
+ /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4
+ ///
+ ///
+ /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json()))
+ ///
+ public async global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsync(
+ string id,
+ global::StabilityAI.FetchAudioResultAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await FetchAudioResultAsBytesAsResponseAsync(
+ id: id,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete.
+ ///
+ ///
+ /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4
+ ///
+ ///
+ /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json()))
+ ///
+ public async global::System.Threading.Tasks.Task FetchAudioResultAsBytesAsStreamAsync(
+ string id,
+ global::StabilityAI.FetchAudioResultAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ PrepareArguments(
+ client: HttpClient);
+ PrepareFetchAudioResultAsBytesArguments(
+ httpClient: HttpClient,
+ id: ref id,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_FetchAudioResultAsBytesSecurityRequirements,
+ operationName: "FetchAudioResultAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: true);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: $"/v2beta/audio/results/{id}",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Get,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "audio/mpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareFetchAudioResultAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ id: id!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessFetchAudioResultAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.FetchAudioResultResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // id: the generation either does not exist or has expired.
+ if ((int)__response.StatusCode == 404)
+ {
+ string? __content_404 = null;
+ global::System.Exception? __exception_404 = null;
+ global::StabilityAI.FetchAudioResultResponse5? __value_404 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext);
+ }
+ else
+ {
+ __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_404 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_404 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_404,
+ responseBody: __content_404,
+ responseObject: __value_404,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.FetchAudioResultResponse6? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Fetch Audio Result
+ /// Fetch the result of an audio generation by ID.
+ /// Poll this endpoint after starting an async audio generation. Returns `202` while
+ /// in-progress, `200` with the audio when complete.
+ ///
+ ///
+ /// The `id` of a generation, typically used for async generations, that can be used to check the status of the generation or retrieve the result.
+ /// Example: a6dc6c6e20acda010fe14d71f180658f2896ed9b4ec25aa99a6ff06c796987c4
+ ///
+ ///
+ /// Specify `audio/*` to receive the bytes of the audio directly. Otherwise specify `application/json` to receive the audio as base64 encoded JSON.
+ /// Default Value: audio/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// generation_id = "e52772ac75b..."
+ /// result = requests.get(
+ /// f"https://api.stability.ai/v2beta/audio/results/{generation_id}",
+ /// headers={"authorization": f"Bearer sk-MYAPIKEY", "accept": "audio/*"},
+ /// )
+ /// if result.status_code == 202:
+ /// print("Generation is still in-progress.")
+ /// elif result.status_code == 200:
+ /// with open("./output.mp3", "wb") as f:
+ /// f.write(result.content)
+ /// print("Download complete!")
+ /// else:
+ /// raise Exception(str(result.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> FetchAudioResultAsBytesAsResponseAsync(
+ string id,
+ global::StabilityAI.FetchAudioResultAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ PrepareArguments(
+ client: HttpClient);
+ PrepareFetchAudioResultAsBytesArguments(
+ httpClient: HttpClient,
+ id: ref id,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_FetchAudioResultAsBytesSecurityRequirements,
+ operationName: "FetchAudioResultAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: true);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: $"/v2beta/audio/results/{id}",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Get,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "audio/mpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareFetchAudioResultAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ id: id!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessFetchAudioResultAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "FetchAudioResultAsBytes",
+ methodName: "FetchAudioResultAsBytesAsync",
+ pathTemplate: "$\"/v2beta/audio/results/{id}\"",
+ httpMethod: "GET",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.FetchAudioResultResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.FetchAudioResultResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // id: the generation either does not exist or has expired.
+ if ((int)__response.StatusCode == 404)
+ {
+ string? __content_404 = null;
+ global::System.Exception? __exception_404 = null;
+ global::StabilityAI.FetchAudioResultResponse5? __value_404 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext);
+ }
+ else
+ {
+ __content_404 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_404 = global::StabilityAI.FetchAudioResultResponse5.FromJson(__content_404, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_404 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_404 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_404,
+ responseBody: __content_404,
+ responseObject: __value_404,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.FetchAudioResultResponse6? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.FetchAudioResultResponse6.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessFetchAudioResultAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs
index 2be8dde..fdde785 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketch.g.cs
@@ -291,6 +291,10 @@ partial void ProcessCreateStableImageControlSketchResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -328,42 +332,6 @@ partial void ProcessCreateStableImageControlSketchResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -1311,6 +1279,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1348,42 +1320,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -2180,6 +2116,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2217,42 +2157,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs
new file mode 100644
index 0000000..a2a007a
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlSketchAsBytes.g.cs
@@ -0,0 +1,4268 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class ControlClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlSketchAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlSketchAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageControlSketchAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageControlSketchAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageControlSketchAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlSketchRequest request);
+ partial void PrepareCreateStableImageControlSketchAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlSketchRequest request);
+ partial void ProcessCreateStableImageControlSketchAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageControlSketchAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlSketchRequest request,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageControlSketchAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlSketchRequest request,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlSketchAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlSketchAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/sketch",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlSketchAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlSketchAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlSketchRequest request,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlSketchAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlSketchAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/sketch",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlSketchAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlSketchAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlSketchAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync(
+ string contentType,
+ string prompt,
+ byte[] image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __request = new global::StabilityAI.CreateStableImageControlSketchRequest
+ {
+ Prompt = prompt,
+ Image = image,
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+
+ return await CreateStableImageControlSketchAsBytesAsync(
+ contentType: contentType,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: __request,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlSketchRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlSketchAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlSketchAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/sketch",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlSketchAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlSketchAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlSketchAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlSketchAsBytesAsStreamAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlSketchRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlSketchAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlSketchAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/sketch",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlSketchAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlSketchAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Sketch
+ /// This service offers an ideal solution for design projects that require brainstorming and
+ /// frequent iterations. It upgrades rough hand-drawn sketches to refined outputs with precise
+ /// control. For non-sketch images, it allows detailed manipulation of the final appearance by
+ /// leveraging the contour lines and edges within the image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=ZKIAqHzJzzUo)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Image Dimensions:
+ /// - Every side must be at least 64 pixels
+ /// - The total pixel count cannot exceed 9,437,184 pixels (e.g. 3072x3072, 4096x2304, etc.)
+ /// Image Aspect Ratio:
+ /// - Must be between 1:2.5 and 2.5:1 (i.e. cannot be too tall or too wide)
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/sketch",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./sketch.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a medieval castle on a hill",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./castle.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlSketchAsBytesAsResponseAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlSketchAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlSketchRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlSketchRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlSketchAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlSketchAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlSketchAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/sketch",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlSketchAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlSketchAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlSketchAsBytes",
+ methodName: "CreateStableImageControlSketchAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/sketch\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlSketchResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlSketchResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlSketchResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlSketchResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlSketchResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlSketchResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlSketchAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs
index acae1df..1ba8897 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructure.g.cs
@@ -289,6 +289,10 @@ partial void ProcessCreateStableImageControlStructureResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -326,42 +330,6 @@ partial void ProcessCreateStableImageControlStructureResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -1307,6 +1275,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1344,42 +1316,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -2175,6 +2111,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2212,42 +2152,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs
new file mode 100644
index 0000000..6a6d5d4
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStructureAsBytes.g.cs
@@ -0,0 +1,4261 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class ControlClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStructureAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStructureAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageControlStructureAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageControlStructureAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageControlStructureAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStructureRequest request);
+ partial void PrepareCreateStableImageControlStructureAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStructureRequest request);
+ partial void ProcessCreateStableImageControlStructureAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageControlStructureAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStructureRequest request,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageControlStructureAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStructureRequest request,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStructureAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStructureAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/structure",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStructureAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStructureAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStructureRequest request,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStructureAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStructureAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/structure",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStructureAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStructureAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStructureAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync(
+ string contentType,
+ string prompt,
+ byte[] image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __request = new global::StabilityAI.CreateStableImageControlStructureRequest
+ {
+ Prompt = prompt,
+ Image = image,
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+
+ return await CreateStableImageControlStructureAsBytesAsync(
+ contentType: contentType,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: __request,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStructureRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStructureAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStructureAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/structure",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStructureAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStructureAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStructureAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStructureAsBytesAsStreamAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStructureRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStructureAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStructureAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/structure",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStructureAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStructureAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Structure
+ /// This service excels in generating images by maintaining the structure of an input image,
+ /// making it especially valuable for advanced content creation scenarios such as recreating
+ /// scenes or rendering characters from models.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=59RaZazXz0AU)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `control_strength`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will match that of the input image.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose structure you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// How much influence, or control, the `image` has on the generation. Represented as a float between 0 and 1, where 0 is the least influence and 1 is the maximum.
+ /// Default Value: 0.7F
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/structure",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cat-statue.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a well manicured shrub in an english garden",
+ /// "control_strength": 0.7,
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./shrub-in-a-garden.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStructureAsBytesAsResponseAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStructureAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ double? controlStrength = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStructureRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStructureRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ ControlStrength = controlStrength,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStructureAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStructureAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStructureAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/structure",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.ControlStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ControlStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"control_strength\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStructureAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStructureAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStructureAsBytes",
+ methodName: "CreateStableImageControlStructureAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/structure\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStructureResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStructureResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStructureResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStructureResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStructureResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStructureResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStructureAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs
index a0fc74f..9724bfb 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyle.g.cs
@@ -285,6 +285,10 @@ partial void ProcessCreateStableImageControlStyleResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -322,42 +326,6 @@ partial void ProcessCreateStableImageControlStyleResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -1320,6 +1288,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1357,42 +1329,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
@@ -2200,6 +2136,10 @@ request.Imagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2237,42 +2177,6 @@ request.Imagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
__httpRequestContent.Add(
content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
name: "\"prompt\"");
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs
new file mode 100644
index 0000000..20865d7
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleAsBytes.g.cs
@@ -0,0 +1,4312 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class ControlClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStyleAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStyleAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageControlStyleAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageControlStyleAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageControlStyleAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStyleRequest request);
+ partial void PrepareCreateStableImageControlStyleAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStyleRequest request);
+ partial void ProcessCreateStableImageControlStyleAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageControlStyleAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleRequest request,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageControlStyleAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleRequest request,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.AspectRatio != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"aspect_ratio\"");
+
+ }
+ if (request.Fidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"fidelity\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleRequest request,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.AspectRatio != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"aspect_ratio\"");
+
+ }
+ if (request.Fidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"fidelity\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync(
+ string contentType,
+ string prompt,
+ byte[] image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? negativePrompt = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default,
+ double? fidelity = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __request = new global::StabilityAI.CreateStableImageControlStyleRequest
+ {
+ Prompt = prompt,
+ Image = image,
+ Imagename = imagename,
+ NegativePrompt = negativePrompt,
+ AspectRatio = aspectRatio,
+ Fidelity = fidelity,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+
+ return await CreateStableImageControlStyleAsBytesAsync(
+ contentType: contentType,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: __request,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? negativePrompt = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default,
+ double? fidelity = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStyleRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ NegativePrompt = negativePrompt,
+ AspectRatio = aspectRatio,
+ Fidelity = fidelity,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.AspectRatio != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"aspect_ratio\"");
+
+ }
+ if (request.Fidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"fidelity\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleAsBytesAsStreamAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? negativePrompt = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default,
+ double? fidelity = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStyleRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ NegativePrompt = negativePrompt,
+ AspectRatio = aspectRatio,
+ Fidelity = fidelity,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.AspectRatio != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"aspect_ratio\"");
+
+ }
+ if (request.Fidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"fidelity\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Guide
+ /// This service extracts stylistic elements from an input image (control image) and uses it to guide the creation of an output image based on the prompt. The result is a new image in the same style as the control image.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=y0WKjG72RvTE)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `image`
+ /// - `prompt`
+ /// The body may optionally include:
+ /// - `negative_prompt`
+ /// - `aspect_ratio`
+ /// - `fidelity`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP. The default resolution is 1024x1024.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image whose style you wish to use as the foundation for a generation.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// Controls the aspect ratio of the generated image.
+ /// Default Value: 1:1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.5F
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ ///
+ /// Guides the image model towards a particular style.
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./cinematic-portrait.png", "rb")
+ /// },
+ /// data={
+ /// "prompt": "a majestic portrait of a chicken",
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./chicken-portrait.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleAsBytesAsResponseAsync(
+ string contentType,
+ string prompt,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageControlStyleAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? negativePrompt = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestAspectRatio? aspectRatio = default,
+ double? fidelity = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.CreateStableImageControlStyleRequestStylePreset? stylePreset = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageControlStyleRequest
+ {
+ Prompt = prompt,
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ NegativePrompt = negativePrompt,
+ AspectRatio = aspectRatio,
+ Fidelity = fidelity,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ StylePreset = stylePreset,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.AspectRatio != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.AspectRatio).HasValue ? (request.AspectRatio).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"aspect_ratio\"");
+
+ }
+ if (request.Fidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Fidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"fidelity\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleAsBytes",
+ methodName: "CreateStableImageControlStyleAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs
index bbf7550..36828af 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransfer.g.cs
@@ -297,6 +297,10 @@ partial void ProcessCreateStableImageControlStyleTransferResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -334,42 +338,6 @@ partial void ProcessCreateStableImageControlStyleTransferResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty());
__contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.InitImagename is null
@@ -1453,6 +1421,10 @@ request.StyleImagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1490,42 +1462,6 @@ request.StyleImagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentInitImage = new global::System.Net.Http.StreamContent(initImage);
__contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.InitImagename is null
@@ -2415,6 +2351,10 @@ request.StyleImagename is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2452,42 +2392,6 @@ request.StyleImagename is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentInitImage = new global::System.Net.Http.StreamContent(initImage);
__contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.InitImagename is null
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs
new file mode 100644
index 0000000..1f18c13
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.ControlClient.CreateStableImageControlStyleTransferAsBytes.g.cs
@@ -0,0 +1,4699 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class ControlClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageControlStyleTransferAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageControlStyleTransferAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequest request);
+ partial void PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequest request);
+ partial void ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageControlStyleTransferAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleTransferRequest request,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageControlStyleTransferAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleTransferRequest request,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleTransferAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style-transfer",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty());
+ __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.InitImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentInitImage,
+ name: "\"init_image\"",
+ fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty);
+ if (__contentInitImage.Headers.ContentDisposition != null)
+ {
+ __contentInitImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ var __contentStyleImage = new global::System.Net.Http.ByteArrayContent(request.StyleImage ?? global::System.Array.Empty());
+ __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.StyleImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentStyleImage,
+ name: "\"style_image\"",
+ fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty);
+ if (__contentStyleImage.Headers.ContentDisposition != null)
+ {
+ __contentStyleImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Prompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.StyleStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"style_strength\"");
+
+ }
+ if (request.CompositionFidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"composition_fidelity\"");
+
+ }
+ if (request.ChangeStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"change_strength\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageControlStyleTransferRequest request,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleTransferAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style-transfer",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentInitImage = new global::System.Net.Http.ByteArrayContent(request.InitImage ?? global::System.Array.Empty());
+ __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.InitImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentInitImage,
+ name: "\"init_image\"",
+ fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty);
+ if (__contentInitImage.Headers.ContentDisposition != null)
+ {
+ __contentInitImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ var __contentStyleImage = new global::System.Net.Http.ByteArrayContent(request.StyleImage ?? global::System.Array.Empty());
+ __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.StyleImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentStyleImage,
+ name: "\"style_image\"",
+ fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty);
+ if (__contentStyleImage.Headers.ContentDisposition != null)
+ {
+ __contentStyleImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Prompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.StyleStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"style_strength\"");
+
+ }
+ if (request.CompositionFidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"composition_fidelity\"");
+
+ }
+ if (request.ChangeStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"change_strength\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleTransferAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// How much the original image should change
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync(
+ string contentType,
+ byte[] initImage,
+ string initImagename,
+ byte[] styleImage,
+ string styleImagename,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? prompt = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ double? styleStrength = default,
+ double? compositionFidelity = default,
+ double? changeStrength = default,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest
+ {
+ InitImage = initImage,
+ InitImagename = initImagename,
+ StyleImage = styleImage,
+ StyleImagename = styleImagename,
+ Prompt = prompt,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ StyleStrength = styleStrength,
+ CompositionFidelity = compositionFidelity,
+ ChangeStrength = changeStrength,
+ OutputFormat = outputFormat,
+ };
+
+ return await CreateStableImageControlStyleTransferAsBytesAsync(
+ contentType: contentType,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: __request,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// How much the original image should change
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsync(
+ string contentType,
+ global::System.IO.Stream initImage,
+ string initImagename,
+ global::System.IO.Stream styleImage,
+ string styleImagename,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? prompt = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ double? styleStrength = default,
+ double? compositionFidelity = default,
+ double? changeStrength = default,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage));
+ styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage));
+ var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest
+ {
+ InitImage = global::System.Array.Empty(),
+ InitImagename = initImagename,
+ StyleImage = global::System.Array.Empty(),
+ StyleImagename = styleImagename,
+ Prompt = prompt,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ StyleStrength = styleStrength,
+ CompositionFidelity = compositionFidelity,
+ ChangeStrength = changeStrength,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleTransferAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style-transfer",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentInitImage = new global::System.Net.Http.StreamContent(initImage);
+ __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.InitImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentInitImage,
+ name: "\"init_image\"",
+ fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty);
+ if (__contentInitImage.Headers.ContentDisposition != null)
+ {
+ __contentInitImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage);
+ __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.StyleImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentStyleImage,
+ name: "\"style_image\"",
+ fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty);
+ if (__contentStyleImage.Headers.ContentDisposition != null)
+ {
+ __contentStyleImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Prompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.StyleStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"style_strength\"");
+
+ }
+ if (request.CompositionFidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"composition_fidelity\"");
+
+ }
+ if (request.ChangeStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"change_strength\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleTransferAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// How much the original image should change
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageControlStyleTransferAsBytesAsStreamAsync(
+ string contentType,
+ global::System.IO.Stream initImage,
+ string initImagename,
+ global::System.IO.Stream styleImage,
+ string styleImagename,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? prompt = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ double? styleStrength = default,
+ double? compositionFidelity = default,
+ double? changeStrength = default,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage));
+ styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage));
+ var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest
+ {
+ InitImage = global::System.Array.Empty(),
+ InitImagename = initImagename,
+ StyleImage = global::System.Array.Empty(),
+ StyleImagename = styleImagename,
+ Prompt = prompt,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ StyleStrength = styleStrength,
+ CompositionFidelity = compositionFidelity,
+ ChangeStrength = changeStrength,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleTransferAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style-transfer",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentInitImage = new global::System.Net.Http.StreamContent(initImage);
+ __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.InitImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentInitImage,
+ name: "\"init_image\"",
+ fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty);
+ if (__contentInitImage.Headers.ContentDisposition != null)
+ {
+ __contentInitImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage);
+ __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.StyleImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentStyleImage,
+ name: "\"style_image\"",
+ fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty);
+ if (__contentStyleImage.Headers.ContentDisposition != null)
+ {
+ __contentStyleImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Prompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.StyleStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"style_strength\"");
+
+ }
+ if (request.CompositionFidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"composition_fidelity\"");
+
+ }
+ if (request.ChangeStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"change_strength\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Style Transfer
+ /// Style Transfer applies visual characteristics from reference style images to target images.
+ /// While Style Guide extracts stylistic elements from an input image (control image) and uses it
+ /// to guide the creation of an output image based on the prompt, Style Transfer specifically
+ /// transforms existing content while preserving the original composition.
+ /// This tool helps create consistent content across multiple assets.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to
+ /// [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=YCrxdv5LzqJ9)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request should include:
+ /// - `init_image`
+ /// - `style_image`
+ /// The body may optionally include:
+ /// - `prompt`
+ /// - `negative_prompt`
+ /// - `style_strength`
+ /// - `composition_fidelity`
+ /// - `change_strength`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 1MP, with the same aspect ratio as the `init_image`.
+ /// ### Credits
+ /// Flat rate of 8 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the subject you wish to restyle.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// - The aspect ratio must be between 1:2.5 and 2.5:1
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// An image containing the new style.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Width must be between 64 and 16,383 pixels
+ /// - Height must be between 64 and 16,383 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// What you wish to see in the output image. A strong, descriptive prompt that clearly defines
+ /// elements, colors, and subjects will lead to better results.
+ /// To control the weight of a given word use the format `(word:weight)`,
+ /// where `word` is the word you'd like to control the weight of and `weight`
+ /// is a value between 0 and 1. For example: `The sky was a crisp (blue:0.3) and (green:0.8)`
+ /// would convey a sky that was blue and green, but more green than blue.
+ ///
+ ///
+ /// A blurb of text describing what you **do not** wish to see in the output image.
+ /// This is an advanced feature.
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Sometimes referred to as _denoising_, this parameter controls how much influence the
+ /// `style_image` parameter has on the generated image. A value of 0 would yield an image that
+ /// is identical to the input. A value of 1 would be as if you passed in no image at all.
+ /// Default Value: 1
+ ///
+ ///
+ /// How closely the output image's style resembles the input image's style.
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// How much the original image should change
+ /// Default Value: 0.9F
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/control/style-transfer",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "init_image": open("./chicken-portrait.png", "rb"),
+ /// "style_image": open("./glowbot.png", "rb")
+ /// },
+ /// data={
+ /// "output_format": "webp"
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./glow-chicken.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageControlStyleTransferAsBytesAsResponseAsync(
+ string contentType,
+ global::System.IO.Stream initImage,
+ string initImagename,
+ global::System.IO.Stream styleImage,
+ string styleImagename,
+ global::StabilityAI.CreateStableImageControlStyleTransferAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ string? prompt = default,
+ string? negativePrompt = default,
+ double? seed = default,
+ double? styleStrength = default,
+ double? compositionFidelity = default,
+ double? changeStrength = default,
+ global::StabilityAI.CreateStableImageControlStyleTransferRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ initImage = initImage ?? throw new global::System.ArgumentNullException(nameof(initImage));
+ styleImage = styleImage ?? throw new global::System.ArgumentNullException(nameof(styleImage));
+ var request = new global::StabilityAI.CreateStableImageControlStyleTransferRequest
+ {
+ InitImage = global::System.Array.Empty(),
+ InitImagename = initImagename,
+ StyleImage = global::System.Array.Empty(),
+ StyleImagename = styleImagename,
+ Prompt = prompt,
+ NegativePrompt = negativePrompt,
+ Seed = seed,
+ StyleStrength = styleStrength,
+ CompositionFidelity = compositionFidelity,
+ ChangeStrength = changeStrength,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageControlStyleTransferAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageControlStyleTransferAsBytesSecurityRequirements,
+ operationName: "CreateStableImageControlStyleTransferAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/control/style-transfer",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/png");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentInitImage = new global::System.Net.Http.StreamContent(initImage);
+ __contentInitImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.InitImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.InitImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentInitImage,
+ name: "\"init_image\"",
+ fileName: request.InitImagename != null ? $"\"{request.InitImagename}\"" : string.Empty);
+ if (__contentInitImage.Headers.ContentDisposition != null)
+ {
+ __contentInitImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ var __contentStyleImage = new global::System.Net.Http.StreamContent(styleImage);
+ __contentStyleImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.StyleImagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.StyleImagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentStyleImage,
+ name: "\"style_image\"",
+ fileName: request.StyleImagename != null ? $"\"{request.StyleImagename}\"" : string.Empty);
+ if (__contentStyleImage.Headers.ContentDisposition != null)
+ {
+ __contentStyleImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Prompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ }
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.StyleStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.StyleStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"style_strength\"");
+
+ }
+ if (request.CompositionFidelity != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.CompositionFidelity, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"composition_fidelity\"");
+
+ }
+ if (request.ChangeStrength != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.ChangeStrength, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"change_strength\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageControlStyleTransferAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageControlStyleTransferAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageControlStyleTransferAsBytes",
+ methodName: "CreateStableImageControlStyleTransferAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/control/style-transfer\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageControlStyleTransferResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageControlStyleTransferResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was well-formed, but rejected. See the `errors` field for details.
+ if ((int)__response.StatusCode == 422)
+ {
+ string? __content_422 = null;
+ global::System.Exception? __exception_422 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse6? __value_422 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ else
+ {
+ __content_422 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_422 = global::StabilityAI.CreateStableImageControlStyleTransferResponse6.FromJson(__content_422, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_422 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_422 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_422,
+ responseBody: __content_422,
+ responseObject: __value_422,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse7? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageControlStyleTransferResponse7.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageControlStyleTransferResponse8? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageControlStyleTransferResponse8.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageControlStyleTransferAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs
index a6b2f02..40c5c59 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditErase.g.cs
@@ -283,6 +283,10 @@ partial void ProcessCreateStableImageEditEraseResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -320,42 +324,6 @@ partial void ProcessCreateStableImageEditEraseResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
@@ -1307,6 +1275,10 @@ request.Maskname is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1344,42 +1316,6 @@ request.Maskname is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.StreamContent(image);
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
@@ -2170,6 +2106,10 @@ request.Maskname is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2207,42 +2147,6 @@ request.Maskname is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.StreamContent(image);
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs
new file mode 100644
index 0000000..5c0e7e1
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditEraseAsBytes.g.cs
@@ -0,0 +1,4218 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class EditClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditEraseAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditEraseAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageEditEraseAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageEditEraseAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageEditEraseAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageEditEraseRequest request);
+ partial void PrepareCreateStableImageEditEraseAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageEditEraseRequest request);
+ partial void ProcessCreateStableImageEditEraseAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageEditEraseAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageEditEraseRequest request,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageEditEraseAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageEditEraseRequest request,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditEraseAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditEraseAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/erase",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty());
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditEraseAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditEraseAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageEditEraseRequest request,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditEraseAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditEraseAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/erase",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (request.Mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty());
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditEraseAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditEraseAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageEditEraseAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync(
+ string contentType,
+ byte[] image,
+ string imagename,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ byte[]? mask = default,
+ string? maskname = default,
+ double? growMask = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __request = new global::StabilityAI.CreateStableImageEditEraseRequest
+ {
+ Image = image,
+ Imagename = imagename,
+ Mask = mask,
+ Maskname = maskname,
+ GrowMask = growMask,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ };
+
+ return await CreateStableImageEditEraseAsBytesAsync(
+ contentType: contentType,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: __request,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsync(
+ string contentType,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::System.IO.Stream? mask = default,
+ string? maskname = default,
+ double? growMask = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageEditEraseRequest
+ {
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ Mask = global::System.Array.Empty(),
+ Maskname = maskname,
+ GrowMask = growMask,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditEraseAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditEraseAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/erase",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.StreamContent(mask);
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditEraseAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditEraseAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageEditEraseAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return __content;
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditEraseAsBytesAsStreamAsync(
+ string contentType,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::System.IO.Stream? mask = default,
+ string? maskname = default,
+ double? growMask = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageEditEraseRequest
+ {
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ Mask = global::System.Array.Empty(),
+ Maskname = maskname,
+ GrowMask = growMask,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditEraseAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditEraseAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/erase",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.StreamContent(mask);
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditEraseAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditEraseAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ var __content = await __response.Content.ReadAsStreamAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.ResponseStream(__response, __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ }
+ catch
+ {
+ __response.Dispose();
+ throw;
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ ///
+ /// Erase
+ /// The Erase service removes unwanted objects, such as blemishes on portraits or items on desks, using image masks.
+ /// The mask is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `seed`
+ /// - `output_format`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// The image you wish to erase from.
+ /// Supported Formats:
+ /// - jpeg
+ /// - png
+ /// - webp
+ /// Validation Rules:
+ /// - Every side must be at least 64 pixels
+ /// - Total pixel count must be between 4,096 and 9,437,184 pixels
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Controls the strength of the inpainting process on a per-pixel basis, either via a
+ /// second image (passed into this parameter) or via the alpha channel of the `image` parameter.
+ /// **Passing in a Mask**
+ /// The image passed to this parameter should be a black and white image that represents,
+ /// at any pixel, the strength of inpainting based on how dark or light the given pixel is.
+ /// Completely black pixels represent no inpainting strength while completely white pixels
+ /// represent maximum strength.
+ /// In the event the mask is a different size than the `image` parameter, it will be automatically resized.
+ /// **Alpha Channel Support**
+ /// If you don't provide an explicit mask, one will be derived from the alpha channel of the `image` parameter.
+ /// Transparent pixels will be inpainted while opaque pixels will be preserved.
+ /// In the event an `image` with an alpha channel is provided along with a `mask`, the `mask` will take precedence.
+ /// Example: ./some/image.png
+ ///
+ ///
+ /// Grows the edges of the mask outward in all directions by the specified number of pixels. The expanded area around the mask will be blurred, which can help smooth the transition between inpainted content and the original image.
+ /// Try this parameter if you notice seams or rough edges around the inpainted content.
+ /// > Note: Excessive growth may obscure fine details in the mask and/or merge nearby masked regions.
+ /// Default Value: 5
+ ///
+ ///
+ /// A specific value that is used to guide the 'randomness' of the generation. (Omit this parameter or pass `0` to use a random seed.)
+ /// Default Value: 0
+ ///
+ ///
+ /// Dictates the `content-type` of the generated image.
+ /// Default Value: png
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/erase",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./kangaroo-on-the-beach.png", "rb"),
+ /// "mask": open("./mask-of-kangaroo.png", "rb"),
+ /// },
+ /// data={
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./just-the-beach.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task> CreateStableImageEditEraseAsBytesAsResponseAsync(
+ string contentType,
+ global::System.IO.Stream image,
+ string imagename,
+ global::StabilityAI.CreateStableImageEditEraseAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::System.IO.Stream? mask = default,
+ string? maskname = default,
+ double? growMask = default,
+ double? seed = default,
+ global::StabilityAI.CreateStableImageEditEraseRequestOutputFormat? outputFormat = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+
+ image = image ?? throw new global::System.ArgumentNullException(nameof(image));
+ var request = new global::StabilityAI.CreateStableImageEditEraseRequest
+ {
+ Image = global::System.Array.Empty(),
+ Imagename = imagename,
+ Mask = global::System.Array.Empty(),
+ Maskname = maskname,
+ GrowMask = growMask,
+ Seed = seed,
+ OutputFormat = outputFormat,
+ };
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditEraseAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditEraseAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditEraseAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/erase",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.StreamContent(image);
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ if (mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.StreamContent(mask);
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditEraseAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseContentRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ using (__response)
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditEraseAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditEraseAsBytes",
+ methodName: "CreateStableImageEditEraseAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/erase\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditEraseResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_403 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_403,
+ responseBody: __content_403,
+ responseObject: __value_403,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was larger than 10MiB.
+ if ((int)__response.StatusCode == 413)
+ {
+ string? __content_413 = null;
+ global::System.Exception? __exception_413 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse5? __value_413 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ else
+ {
+ __content_413 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_413 = global::StabilityAI.CreateStableImageEditEraseResponse5.FromJson(__content_413, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_413 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_413 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_413,
+ responseBody: __content_413,
+ responseObject: __value_413,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // You have made more than 150 requests in 10 seconds.
+ if ((int)__response.StatusCode == 429)
+ {
+ string? __content_429 = null;
+ global::System.Exception? __exception_429 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse6? __value_429 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ else
+ {
+ __content_429 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_429 = global::StabilityAI.CreateStableImageEditEraseResponse6.FromJson(__content_429, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_429 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_429 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_429,
+ responseBody: __content_429,
+ responseObject: __value_429,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // An internal error occurred. If the problem persists [contact support](https://kb.stability.ai/knowledge-base/kb-tickets/new).
+ if ((int)__response.StatusCode == 500)
+ {
+ string? __content_500 = null;
+ global::System.Exception? __exception_500 = null;
+ global::StabilityAI.CreateStableImageEditEraseResponse7? __value_500 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ else
+ {
+ __content_500 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_500 = global::StabilityAI.CreateStableImageEditEraseResponse7.FromJson(__content_500, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_500 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_500 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_500,
+ responseBody: __content_500,
+ responseObject: __value_500,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+
+ if (__effectiveReadResponseAsString)
+ {
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ ProcessCreateStableImageEditEraseAsBytesResponseContent(
+ httpClient: HttpClient,
+ httpResponseMessage: __response,
+ content: ref __content);
+
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: null,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+ else
+ {
+ try
+ {
+ __response.EnsureSuccessStatusCode();
+ var __content = await __response.Content.ReadAsByteArrayAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+
+ return new global::StabilityAI.AutoSDKHttpResponse(
+ statusCode: __response.StatusCode,
+ headers: global::StabilityAI.AutoSDKHttpResponse.CreateHeaders(__response),
+ requestUri: __response.RequestMessage?.RequestUri,
+ body: __content);
+ }
+ catch (global::System.Exception __ex)
+ {
+ string? __content = null;
+ try
+ {
+ __content = await __response.Content.ReadAsStringAsync(
+ #if NET5_0_OR_GREATER
+ __effectiveCancellationToken
+ #endif
+ ).ConfigureAwait(false);
+ }
+ catch (global::System.Exception)
+ {
+ }
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __ex,
+ responseBody: __content,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ }
+
+ }
+ }
+ finally
+ {
+ __httpRequest?.Dispose();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs
index 86cee7c..d973fe9 100644
--- a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs
+++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaint.g.cs
@@ -293,6 +293,10 @@ partial void ProcessCreateStableImageEditInpaintResponseContent(
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -330,42 +334,6 @@ partial void ProcessCreateStableImageEditInpaintResponseContent(
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
@@ -1425,6 +1393,10 @@ request.Maskname is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -1462,42 +1434,6 @@ request.Maskname is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.StreamContent(image);
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
@@ -2371,6 +2307,10 @@ request.Maskname is null
__httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
#endif
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "application/json");
+
foreach (var __authorization in __authorizations)
{
if (__authorization.Type == "Http" ||
@@ -2408,42 +2348,6 @@ request.Maskname is null
var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(contentType ?? string.Empty),
- name: "\"content-type\"");
-
- if (accept != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent((accept).HasValue ? (accept).GetValueOrDefault().ToValueString() : string.Empty),
- name: "\"accept\"");
-
- }
- if (stabilityClientId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientId ?? string.Empty),
- name: "\"stability-client-id\"");
-
- }
- if (stabilityClientUserId != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientUserId ?? string.Empty),
- name: "\"stability-client-user-id\"");
-
- }
- if (stabilityClientVersion != default)
- {
-
- __httpRequestContent.Add(
- content: new global::System.Net.Http.StringContent(stabilityClientVersion ?? string.Empty),
- name: "\"stability-client-version\"");
-
- }
var __contentImage = new global::System.Net.Http.StreamContent(image);
__contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
request.Imagename is null
diff --git a/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs
new file mode 100644
index 0000000..93da1bc
--- /dev/null
+++ b/src/libs/StabilityAI/Generated/StabilityAI.EditClient.CreateStableImageEditInpaintAsBytes.g.cs
@@ -0,0 +1,4621 @@
+
+#nullable enable
+
+namespace StabilityAI
+{
+ public partial class EditClient
+ {
+
+
+ private static readonly global::StabilityAI.EndPointSecurityRequirement s_CreateStableImageEditInpaintAsBytesSecurityRequirement0 =
+ new global::StabilityAI.EndPointSecurityRequirement
+ {
+ Authorizations = new global::StabilityAI.EndPointAuthorizationRequirement[]
+ { new global::StabilityAI.EndPointAuthorizationRequirement
+ {
+ Type = "Http",
+ SchemeId = "HttpBearer",
+ Location = "Header",
+ Name = "Bearer",
+ FriendlyName = "Bearer",
+ },
+ },
+ };
+ private static readonly global::StabilityAI.EndPointSecurityRequirement[] s_CreateStableImageEditInpaintAsBytesSecurityRequirements =
+ new global::StabilityAI.EndPointSecurityRequirement[]
+ { s_CreateStableImageEditInpaintAsBytesSecurityRequirement0,
+ };
+ partial void PrepareCreateStableImageEditInpaintAsBytesArguments(
+ global::System.Net.Http.HttpClient httpClient,
+ ref string contentType,
+ ref global::StabilityAI.CreateStableImageEditInpaintAccept? accept,
+ ref string? stabilityClientId,
+ ref string? stabilityClientUserId,
+ ref string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageEditInpaintRequest request);
+ partial void PrepareCreateStableImageEditInpaintAsBytesRequest(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpRequestMessage httpRequestMessage,
+ string contentType,
+ global::StabilityAI.CreateStableImageEditInpaintAccept? accept,
+ string? stabilityClientId,
+ string? stabilityClientUserId,
+ string? stabilityClientVersion,
+ global::StabilityAI.CreateStableImageEditInpaintRequest request);
+ partial void ProcessCreateStableImageEditInpaintAsBytesResponse(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage);
+
+ partial void ProcessCreateStableImageEditInpaintAsBytesResponseContent(
+ global::System.Net.Http.HttpClient httpClient,
+ global::System.Net.Http.HttpResponseMessage httpResponseMessage,
+ ref byte[] content);
+
+ ///
+ /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageEditInpaintRequest request,
+ global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ var __response = await CreateStableImageEditInpaintAsBytesAsResponseAsync(
+ contentType: contentType,
+
+ request: request,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken
+ ).ConfigureAwait(false);
+
+ return __response.Body;
+ }
+ ///
+ /// Inpaint
+ /// Intelligently modify images by filling in or replacing specified areas with new content based
+ /// on the content of a "mask" image.
+ /// The "mask" is provided in one of two ways:
+ /// 1. Explicitly passing in a separate image via the `mask` parameter
+ /// 2. Derived from the alpha channel of the `image` parameter.
+ /// ### Try it out
+ /// Grab your [API key](https://platform.stability.ai/account/keys) and head over to [](https://colab.research.google.com/github/stability-ai/stability-sdk/blob/main/nbs/Stable_Image_API_Public.ipynb#scrollTo=t1Q4w2uvvza0)
+ /// ### How to use
+ /// Please invoke this endpoint with a `POST` request.
+ /// The headers of the request must include an API key in the `authorization` field. The body of the request must be
+ /// `multipart/form-data`, and the `accept` header should be set to one of the following:
+ /// - `image/*` to receive the image in the format specified by the `output_format` parameter.
+ /// - `application/json` to receive the image encoded as base64 in a JSON response.
+ /// The body of the request must include:
+ /// - `image`
+ /// - `prompt`
+ /// Optionally, the body of the request may also include:
+ /// - `mask`
+ /// - `negative_prompt`
+ /// - `seed`
+ /// - `output_format`
+ /// - `style_preset`
+ /// > **Note:** for more details about these parameters please see the request schema below.
+ /// ### Output
+ /// The resolution of the generated image will be 4 megapixels.
+ /// ### Credits
+ /// Flat rate of 5 credits per successful generation. You will not be charged for failed generations.
+ ///
+ ///
+ /// The content type of the request body. Do not manually specify this header; your HTTP client library will automatically include the appropriate boundary parameter.
+ /// Example: multipart/form-data
+ ///
+ ///
+ /// Specify `image/*` to receive the bytes of the image directly. Otherwise specify `application/json` to receive the image as base64 encoded JSON.
+ /// Default Value: image/*
+ ///
+ ///
+ /// The name of your application, used to help us communicate app-specific debugging or moderation issues to you.
+ /// Example: my-awesome-app
+ ///
+ ///
+ /// A unique identifier for your end user. Used to help us communicate user-specific debugging or moderation issues to you. Feel free to obfuscate this value to protect user privacy.
+ /// Example: DiscordUser#9999
+ ///
+ ///
+ /// The version of your application, used to help us communicate version-specific debugging or moderation issues to you.
+ /// Example: 1.2.1
+ ///
+ ///
+ /// Per-request overrides such as headers, query parameters, timeout, retries, and response buffering.
+ /// The token to cancel the operation with
+ ///
+ ///
+ /// import requests
+ /// response = requests.post(
+ /// f"https://api.stability.ai/v2beta/stable-image/edit/inpaint",
+ /// headers={
+ /// "authorization": f"Bearer sk-MYAPIKEY",
+ /// "accept": "image/*"
+ /// },
+ /// files={
+ /// "image": open("./dog-wearing-vr-goggles.png", "rb"),
+ /// "mask": open("./mask.png", "rb"),
+ /// },
+ /// data={
+ /// "prompt": "dog wearing black glasses",
+ /// "output_format": "webp",
+ /// },
+ /// )
+ /// if response.status_code == 200:
+ /// with open("./dog-wearing-black-glasses.webp", 'wb') as file:
+ /// file.write(response.content)
+ /// else:
+ /// raise Exception(str(response.json()))
+ ///
+ public async global::System.Threading.Tasks.Task CreateStableImageEditInpaintAsBytesAsStreamAsync(
+ string contentType,
+
+ global::StabilityAI.CreateStableImageEditInpaintRequest request,
+ global::StabilityAI.CreateStableImageEditInpaintAccept? accept = default,
+ string? stabilityClientId = default,
+ string? stabilityClientUserId = default,
+ string? stabilityClientVersion = default,
+ global::StabilityAI.AutoSDKRequestOptions? requestOptions = default,
+ global::System.Threading.CancellationToken cancellationToken = default)
+ {
+ request = request ?? throw new global::System.ArgumentNullException(nameof(request));
+
+ PrepareArguments(
+ client: HttpClient);
+ PrepareCreateStableImageEditInpaintAsBytesArguments(
+ httpClient: HttpClient,
+ contentType: ref contentType,
+ accept: ref accept,
+ stabilityClientId: ref stabilityClientId,
+ stabilityClientUserId: ref stabilityClientUserId,
+ stabilityClientVersion: ref stabilityClientVersion,
+ request: request);
+
+
+ var __authorizations = global::StabilityAI.EndPointSecurityResolver.ResolveAuthorizations(
+ availableAuthorizations: Authorizations,
+ securityRequirements: s_CreateStableImageEditInpaintAsBytesSecurityRequirements,
+ operationName: "CreateStableImageEditInpaintAsBytesAsync");
+
+ using var __timeoutCancellationTokenSource = global::StabilityAI.AutoSDKRequestOptionsSupport.CreateTimeoutCancellationTokenSource(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ cancellationToken: cancellationToken);
+ var __effectiveCancellationToken = __timeoutCancellationTokenSource?.Token ?? cancellationToken;
+ var __effectiveReadResponseAsString = global::StabilityAI.AutoSDKRequestOptionsSupport.GetReadResponseAsString(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ fallbackValue: ReadResponseAsString);
+ var __maxAttempts = global::StabilityAI.AutoSDKRequestOptionsSupport.GetMaxAttempts(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ supportsRetry: false);
+
+ global::System.Net.Http.HttpRequestMessage __CreateHttpRequest()
+ {
+
+ var __pathBuilder = new global::StabilityAI.PathBuilder(
+ path: "/v2beta/stable-image/edit/inpaint",
+ baseUri: HttpClient.BaseAddress);
+ var __path = __pathBuilder.ToString();
+ __path = global::StabilityAI.AutoSDKRequestOptionsSupport.AppendQueryParameters(
+ path: __path,
+ clientParameters: Options.QueryParameters,
+ requestParameters: requestOptions?.QueryParameters);
+ var __httpRequest = new global::System.Net.Http.HttpRequestMessage(
+ method: global::System.Net.Http.HttpMethod.Post,
+ requestUri: new global::System.Uri(__path, global::System.UriKind.RelativeOrAbsolute));
+#if NET6_0_OR_GREATER
+ __httpRequest.Version = global::System.Net.HttpVersion.Version11;
+ __httpRequest.VersionPolicy = global::System.Net.Http.HttpVersionPolicy.RequestVersionOrHigher;
+#endif
+
+ __httpRequest.Headers.TryAddWithoutValidation(
+ "Accept",
+ "image/jpeg");
+
+ foreach (var __authorization in __authorizations)
+ {
+ if (__authorization.Type == "Http" ||
+ __authorization.Type == "OAuth2" ||
+ __authorization.Type == "OpenIdConnect")
+ {
+ __httpRequest.Headers.Authorization = new global::System.Net.Http.Headers.AuthenticationHeaderValue(
+ scheme: __authorization.Name,
+ parameter: __authorization.Value);
+ }
+ else if (__authorization.Type == "ApiKey" &&
+ __authorization.Location == "Header")
+ {
+ __httpRequest.Headers.Add(__authorization.Name, __authorization.Value);
+ }
+ }
+
+ __httpRequest.Headers.TryAddWithoutValidation("content-type", contentType.ToString());
+ if (accept != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("accept", accept?.ToValueString() ?? string.Empty);
+ }
+ if (stabilityClientId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-id", stabilityClientId.ToString());
+ }
+ if (stabilityClientUserId != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-user-id", stabilityClientUserId.ToString());
+ }
+ if (stabilityClientVersion != default)
+ {
+ __httpRequest.Headers.TryAddWithoutValidation("stability-client-version", stabilityClientVersion.ToString());
+ }
+
+
+ var __httpRequestContent = new global::System.Net.Http.MultipartFormDataContent();
+ var __contentImage = new global::System.Net.Http.ByteArrayContent(request.Image ?? global::System.Array.Empty());
+ __contentImage.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Imagename is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Imagename) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentImage,
+ name: "\"image\"",
+ fileName: request.Imagename != null ? $"\"{request.Imagename}\"" : string.Empty);
+ if (__contentImage.Headers.ContentDisposition != null)
+ {
+ __contentImage.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.Prompt ?? string.Empty),
+ name: "\"prompt\"");
+
+ if (request.NegativePrompt != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(request.NegativePrompt ?? string.Empty),
+ name: "\"negative_prompt\"");
+
+ }
+ if (request.Mask != default)
+ {
+
+ var __contentMask = new global::System.Net.Http.ByteArrayContent(request.Mask ?? global::System.Array.Empty());
+ __contentMask.Headers.ContentType = new global::System.Net.Http.Headers.MediaTypeHeaderValue(
+ request.Maskname is null
+ ? "application/octet-stream"
+ : (global::System.IO.Path.GetExtension(request.Maskname) ?? string.Empty).ToLowerInvariant() switch
+ {
+ ".aac" => "audio/aac",
+ ".flac" => "audio/flac",
+ ".gif" => "image/gif",
+ ".jpeg" => "image/jpeg",
+ ".jpg" => "image/jpeg",
+ ".json" => "application/json",
+ ".m4a" => "audio/mp4",
+ ".mp3" => "audio/mpeg",
+ ".mp4" => "video/mp4",
+ ".mpeg" => "audio/mpeg",
+ ".mpga" => "audio/mpeg",
+ ".oga" => "audio/ogg",
+ ".ogg" => "audio/ogg",
+ ".opus" => "audio/ogg",
+ ".pdf" => "application/pdf",
+ ".png" => "image/png",
+ ".txt" => "text/plain",
+ ".wav" => "audio/wav",
+ ".weba" => "audio/webm",
+ ".webm" => "video/webm",
+ ".webp" => "image/webp",
+ _ => "application/octet-stream",
+ });
+ __httpRequestContent.Add(
+ content: __contentMask,
+ name: "\"mask\"",
+ fileName: request.Maskname != null ? $"\"{request.Maskname}\"" : string.Empty);
+ if (__contentMask.Headers.ContentDisposition != null)
+ {
+ __contentMask.Headers.ContentDisposition.FileNameStar = null;
+ }
+
+ }
+ if (request.GrowMask != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.GrowMask, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"grow_mask\"");
+
+ }
+ if (request.Seed != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent(global::System.Convert.ToString(request.Seed, global::System.Globalization.CultureInfo.InvariantCulture) ?? string.Empty),
+ name: "\"seed\"");
+
+ }
+ if (request.OutputFormat != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.OutputFormat).HasValue ? (request.OutputFormat).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"output_format\"");
+
+ }
+ if (request.StylePreset != default)
+ {
+
+ __httpRequestContent.Add(
+ content: new global::System.Net.Http.StringContent((request.StylePreset).HasValue ? (request.StylePreset).GetValueOrDefault().ToValueString() : string.Empty),
+ name: "\"style_preset\"");
+
+ }
+
+ __httpRequest.Content = __httpRequestContent;
+
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ApplyHeaders(
+ request: __httpRequest,
+ clientHeaders: Options.Headers,
+ requestHeaders: requestOptions?.Headers);
+
+ PrepareRequest(
+ client: HttpClient,
+ request: __httpRequest);
+ PrepareCreateStableImageEditInpaintAsBytesRequest(
+ httpClient: HttpClient,
+ httpRequestMessage: __httpRequest,
+ contentType: contentType!,
+ accept: accept,
+ stabilityClientId: stabilityClientId,
+ stabilityClientUserId: stabilityClientUserId,
+ stabilityClientVersion: stabilityClientVersion,
+ request: request);
+
+ return __httpRequest;
+ }
+
+ global::System.Net.Http.HttpRequestMessage? __httpRequest = null;
+ global::System.Net.Http.HttpResponseMessage? __response = null;
+ var __attemptNumber = 0;
+ try
+ {
+ for (var __attempt = 1; __attempt <= __maxAttempts; __attempt++)
+ {
+ __attemptNumber = __attempt;
+ __httpRequest = __CreateHttpRequest();
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnBeforeRequestAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditInpaintAsBytes",
+ methodName: "CreateStableImageEditInpaintAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ try
+ {
+ __response = await HttpClient.SendAsync(
+ request: __httpRequest,
+ completionOption: global::System.Net.Http.HttpCompletionOption.ResponseHeadersRead,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ }
+ catch (global::System.Net.Http.HttpRequestException __exception)
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: null,
+ attempt: __attempt);
+ var __willRetry = __attempt < __maxAttempts && !__effectiveCancellationToken.IsCancellationRequested;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditInpaintAsBytes",
+ methodName: "CreateStableImageEditInpaintAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: null,
+ exception: __exception,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: __willRetry,
+ retryDelay: __willRetry ? __retryDelay : (global::System.TimeSpan?)null,
+ retryReason: "exception",
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ if (!__willRetry)
+ {
+ throw;
+ }
+
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (__response != null &&
+ __attempt < __maxAttempts &&
+ global::StabilityAI.AutoSDKRequestOptionsSupport.ShouldRetryStatusCode(__response.StatusCode))
+ {
+ var __retryDelay = global::StabilityAI.AutoSDKRequestOptionsSupport.GetRetryDelay(
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ response: __response,
+ attempt: __attempt);
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditInpaintAsBytes",
+ methodName: "CreateStableImageEditInpaintAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attempt,
+ maxAttempts: __maxAttempts,
+ willRetry: true,
+ retryDelay: __retryDelay,
+ retryReason: "status:" + ((int)__response.StatusCode).ToString(global::System.Globalization.CultureInfo.InvariantCulture),
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ __response.Dispose();
+ __response = null;
+ __httpRequest.Dispose();
+ __httpRequest = null;
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.DelayBeforeRetryAsync(
+ retryDelay: __retryDelay,
+ cancellationToken: __effectiveCancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ break;
+ }
+
+ if (__response == null)
+ {
+ throw new global::System.InvalidOperationException("No response received.");
+ }
+
+ try
+ {
+
+ ProcessResponse(
+ client: HttpClient,
+ response: __response);
+ ProcessCreateStableImageEditInpaintAsBytesResponse(
+ httpClient: HttpClient,
+ httpResponseMessage: __response);
+ if (__response.IsSuccessStatusCode)
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterSuccessAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditInpaintAsBytes",
+ methodName: "CreateStableImageEditInpaintAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ else
+ {
+ await global::StabilityAI.AutoSDKRequestOptionsSupport.OnAfterErrorAsync(
+ clientOptions: Options,
+ context: global::StabilityAI.AutoSDKRequestOptionsSupport.CreateHookContext(
+ operationId: "createStableImageEditInpaintAsBytes",
+ methodName: "CreateStableImageEditInpaintAsBytesAsync",
+ pathTemplate: "\"/v2beta/stable-image/edit/inpaint\"",
+ httpMethod: "POST",
+ baseUri: BaseUri,
+ request: __httpRequest!,
+ response: __response,
+ exception: null,
+ clientOptions: Options,
+ requestOptions: requestOptions,
+ attempt: __attemptNumber,
+ maxAttempts: __maxAttempts,
+ willRetry: false,
+ retryDelay: null,
+ retryReason: global::System.String.Empty,
+ cancellationToken: __effectiveCancellationToken)).ConfigureAwait(false);
+ }
+ // Invalid parameter(s), see the `errors` field for details.
+ if ((int)__response.StatusCode == 400)
+ {
+ string? __content_400 = null;
+ global::System.Exception? __exception_400 = null;
+ global::StabilityAI.CreateStableImageEditInpaintResponse4? __value_400 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ else
+ {
+ __content_400 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_400 = global::StabilityAI.CreateStableImageEditInpaintResponse4.FromJson(__content_400, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_400 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException.Create(
+ statusCode: __response.StatusCode,
+ message: __content_400 ?? __response.ReasonPhrase ?? string.Empty,
+ innerException: __exception_400,
+ responseBody: __content_400,
+ responseObject: __value_400,
+ responseHeaders: global::System.Linq.Enumerable.ToDictionary(
+ __response.Headers,
+ h => h.Key,
+ h => h.Value));
+ }
+ // Your request was flagged by our content moderation system.
+ if ((int)__response.StatusCode == 403)
+ {
+ string? __content_403 = null;
+ global::System.Exception? __exception_403 = null;
+ global::StabilityAI.ContentModerationResponse? __value_403 = null;
+ try
+ {
+ if (__effectiveReadResponseAsString)
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ else
+ {
+ __content_403 = await __response.Content.ReadAsStringAsync(__effectiveCancellationToken).ConfigureAwait(false);
+
+ __value_403 = global::StabilityAI.ContentModerationResponse.FromJson(__content_403, JsonSerializerContext);
+ }
+ }
+ catch (global::System.Exception __ex)
+ {
+ __exception_403 = __ex;
+ }
+
+
+ throw global::StabilityAI.ApiException