openai / openai-dotnet

The official .NET library for the OpenAI API
https://www.nuget.org/packages/OpenAI
MIT License
707 stars 60 forks source link

Missing support for OrganizationID and ProjectID #68

Closed egable closed 1 week ago

egable commented 1 week ago

When I generate an API key, it requires me to use an OrganizationID and ProjectID in conjunction with the API key. There appears to be no mechanism to specify these when creating a client.

https://platform.openai.com/docs/api-reference/authentication

trrwilson commented 1 week ago

Thank you for drawing attention to this, @egable! We'll look into adding this to the client options type (which would be the closest parallel to client instantiation in node/python) as soon as possible.

In the interim, although it's substantially more code, you could use a custom System.ClientModel PipelinePolicy to manually add these or other headers; below is a standalone code example demonstrating that approach.

using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;

#nullable disable

public class AddAuthHeadersPolicy : PipelinePolicy
{
    public string OrganizationId { get; set; }
    public string ProjectId { get; set; }

    public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
    {
        ApplyHeaders(message?.Request?.Headers);
        ProcessNext(message, pipeline, currentIndex);
    }

    public override ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
    {
        ApplyHeaders(message?.Request?.Headers);
        return ProcessNextAsync(message, pipeline, currentIndex);
    }

    private void ApplyHeaders(PipelineRequestHeaders headers)
    {
        if (headers is null)
        {
            return;
        }
        if (!string.IsNullOrEmpty(OrganizationId))
        {
            headers.Set("OpenAI-Organization", OrganizationId);
        }
        if (!string.IsNullOrEmpty(ProjectId))
        {
            headers.Set("OpenAI-Project", ProjectId);
        }
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        AddAuthHeadersPolicy authHeadersPolicy = new()
        {
            ProjectId = "your project ID",
        };
        OpenAIClientOptions clientOptions = new();
        clientOptions.AddPolicy(authHeadersPolicy, PipelinePosition.BeforeTransport);

        ChatClient client = new("gpt-4o", clientOptions);
    }
}