Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit image generation concurrency #75

Merged
merged 1 commit into from
Dec 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions BotNet.Services/BotCommands/OpenAI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,7 @@ await botClient.SendTextMessageAsync(
}
}

private static readonly RateLimiter IMAGE_GENERATION_RATE_LIMITER = RateLimiter.PerUser(1, TimeSpan.FromMinutes(3));
public static async Task StreamChatWithFriendlyBotAsync(
ITelegramBotClient botClient,
IServiceProvider serviceProvider,
Expand Down Expand Up @@ -828,6 +829,10 @@ await serviceProvider.GetRequiredService<FriendlyBot>().StreamChatAsync(
);
break;
case ChatIntent.ImageGeneration:
IMAGE_GENERATION_RATE_LIMITER.ValidateActionRate(
chatId: message.Chat.Id,
userId: message.From.Id
);
Message busyMessage = await botClient.SendTextMessageAsync(
chatId: message.Chat.Id,
text: "Generating image… ⏳",
Expand Down
21 changes: 15 additions & 6 deletions BotNet.Services/OpenAI/Skills/ImageGenerationBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,23 @@ public class ImageGenerationBot(
OpenAIClient openAIClient
) {
private readonly OpenAIClient _openAIClient = openAIClient;
private static readonly SemaphoreSlim SEMAPHORE = new(1, 1);

public Task<Uri> GenerateImageAsync(
public async Task<Uri> GenerateImageAsync(
string prompt,
CancellationToken cancellationToken
) => _openAIClient.GenerateImageAsync(
model: "dall-e-3",
prompt: prompt,
cancellationToken: cancellationToken
);
) {
// dall-e-3 endpoint does not allow concurrent requests
await SEMAPHORE.WaitAsync(cancellationToken);
try {
return await _openAIClient.GenerateImageAsync(
model: "dall-e-3",
prompt: prompt,
cancellationToken: cancellationToken
);
} finally {
SEMAPHORE.Release();
}
}
}
}
Loading