Recursive AI

Moderate text and image input in C#

OneLLM is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Send text and an image to OpenAI’s moderation service using OPENAI_API_KEY, or try the offline download without credentials.

Terminal
dotnet add package RecursiveAI.OneLlm

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneLlm;
using OneLlm.Providers;
using OneLlm.Providers.OpenAI;
 
var key = Environment
    .GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(key))
{
    Console.WriteLine("Set OPENAI_API_KEY.");
    return;
}
IModerationProvider provider =
    new OpenAIProvider(
    new OpenAIOptions { ApiKey = new Secret(key) },
    TimeProvider.System);
var response = await provider.ModerateAsync(new()
{
    Model = "omni-moderation-latest",
    Inputs = ["A blue square."],
    Images = [new ImageInput(
        File.ReadAllBytes("square.png"), "image/png")]
});
Console.WriteLine(
    response.Results[0].Flagged);

square.png is the solid blue square included in the download. Without a key, the snippet prints:

Text
Set OPENAI_API_KEY.

Unzip the example, then dotnet run.

The full program

By default the download runs offline: it uses the real OpenAIProvider with a test HTTP handler that returns the JSON shown in the program. The handler checks that both the text and image were serialized. It does not classify the image.

C#
using OneLlm;
using OneLlm.Providers;
using OneLlm.Providers.OpenAI;
using System.Net;
using System.Text;
using System.Globalization;
 
bool live = args.Contains("--live");
// No key is read and no network request is made in the default, offline mode.
string? key = live ? Environment.GetEnvironmentVariable("OPENAI_API_KEY") : null;
if (live && string.IsNullOrWhiteSpace(key))
    throw new InvalidOperationException("Set OPENAI_API_KEY for --live.");
using var http = live ? new HttpClient() : new HttpClient(new FixtureHandler());
IModerationProvider provider = new OpenAIProvider(new OpenAIOptions
{
    ApiKey = live ? new Secret(key!) : null,
    HttpClient = http
}, TimeProvider.System);
var response = await provider.ModerateAsync(new ModerationRequest
{
    Model = "omni-moderation-latest",
    Inputs = ["A blue square."],
    Images = [new ImageInput(await File.ReadAllBytesAsync("square.png"), "image/png")]
});
Console.WriteLine(live ? "Live service response" : "Offline fixture, not a model verdict");
foreach (var result in response.Results)
{
    Console.WriteLine($"Flagged: {result.Flagged}");
    foreach (var category in result.Categories)
    {
        string score = result.Scores.TryGetValue(category.Key, out double value)
            ? value.ToString("F3", CultureInfo.InvariantCulture) : "not reported";
        Console.WriteLine($"{category.Key}: {category.Value}; score: {score}");
    }
    Console.WriteLine(result.Flagged ? "Policy: hold for review" : "Policy: continue to other checks");
}
 
// Tests the real provider's request writer and response parser, without a service key.
public sealed class FixtureHandler : HttpMessageHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token)
    {
        string body = await request.Content!.ReadAsStringAsync(token);
        if (!body.Contains("image_url") || !body.Contains("A blue square."))
            throw new InvalidOperationException("Expected both text and image.");
        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent("""
            {"id":"fixture","model":"omni-moderation-latest","results":[{
              "flagged":false,"categories":{"violence":false},
              "category_scores":{"violence":0.01},
              "category_applied_input_types":{"violence":["text","image"]}
            }]}
            """, Encoding.UTF8, "application/json")
        };
    }
}
Text
Offline fixture, not a model verdict
Flagged: False
violence: False; score: 0.010
Policy: continue to other checks

The image is an original, generated 16 × 16 blue PNG, included for unrestricted reuse. The text is A blue square.. There are no hidden inputs.

To send these inputs to the real service, set OPENAI_API_KEY privately in your environment, then run dotnet run -- --live. Live scores vary; no live service result is shown here. A missing key stops live mode before the request, and service failures surface as ProviderException.

Treat moderation scores as policy signals, not a guaranteed safety verdict; the handling rule here sends flagged results to review and leaves unflagged results subject to other checks.

Variations

Text only. Replace the full program’s request with the following. It uses the same offline response fixture; remove the handler’s image assertion when testing this variation.

C#
var response = await provider.ModerateAsync(new ModerationRequest
{
    Model = "omni-moderation-latest",
    Inputs = ["A blue square."]
});

The offline output remains:

Text
Offline fixture, not a model verdict
Flagged: False
violence: False; score: 0.010
Policy: continue to other checks

Inspect applicable input types. Add this inside the result loop. On the supplied fixture it prints violence: text, image.

C#
if (result.CategoryInputTypes is { } inputTypes)
    foreach (var category in inputTypes)
        Console.WriteLine($"{category.Key}: {string.Join(", ", category.Value)}");

The short answer

Use IModerationProvider.ModerateAsync with ModerationRequest.Inputs for text and Images for image bytes and content types. The OpenAI provider sends these to the moderation endpoint. Choose omni-moderation-latest for text-and-image input, then inspect Flagged, Categories, Scores and, when provided, CategoryInputTypes.

Your application owns the response policy. The library returns the service’s classification; it does not remove content, suspend users or decide whether a flagged submission deserves a human review. The example makes that distinction visible: “hold for review” is application code, while Flagged and category scores are provider results.

How do I moderate text and images with the OpenAI API in C#?

Construct an OpenAIProvider with your key wrapped in Secret, then pass a request containing both text and ImageInput values. An image input is bytes plus a MIME content type. The pinned media documentation lists the OpenAI moderation endpoint as accepting texts and images in one request.

The provider serializes those images as data URLs. There is no need to host the image publicly. Keep the content type accurate: the PNG example declares image/png, rather than guessing a type from an unrelated file extension. Check your upload size and format before you submit content, using the service’s current moderation documentation.

When images are present, the request checks the text and images together. Do not assume the response has a separate result for each image. For text-only requests, the API shape supports one result per input in order. If your policy needs an independent decision per submission, keep each submission’s text and images together in its own request.

Which OpenAI moderation model accepts images?

OpenAI documents omni-moderation-latest as accepting text and images. This recipe names that model explicitly, rather than relying on a chat model or asking a conversation to classify itself. The OneLLM capability table lists moderation for the OpenAI provider, not the Gemini provider.

Image support does not mean every category applies to images. OpenAI’s category table distinguishes text-only categories from categories that also support images. Read CategoryInputTypes when the provider supplies it. A score for a text-only category is not evidence that an image was checked for that category. A missing input-type dictionary means the provider did not report those details; it is not the same thing as an empty list of applicable input types.

What do moderation flags and scores mean?

Flagged indicates whether a category was flagged, Categories names the per-category flags, and Scores carries the provider’s scores. The library’s public contract describes scores as ranging from zero to one. They are not a promise that content is safe when the flag is false.

The example’s 0.010 is invented fixture data, not a measured score for the blue image. It demonstrates formatting and decision routing. The offline handler deliberately returns only one category so the mechanics remain readable; a live response can include more categories.

Start with a written policy: what requires review, what happens while review is pending, and how a service failure is handled. Do not convert an unavailable response into an unflagged result. If you introduce score thresholds, evaluate them on material relevant to your application. OpenAI notes that model updates can require recalibrating policies based on category scores. Keep your policy separate from the request code so you can revise it without changing how uploads are serialized.

How do I test image moderation without an API key?

Use the download’s default offline path to test request serialization, response parsing and the handling rule. The test HTTP handler never opens a network connection and the default path never reads OPENAI_API_KEY. This lets you test the application without turning each test into a service call.

It cannot measure classification quality. For that you need an authorized live evaluation with appropriate content and a policy for handling it. The live switch and the snippet at the top show the real-provider setup, but the output on this page is explicitly offline. Keep credentials in your environment or secret store, never in source files or printed logs.

All onellm recipes