openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
OpenAI/src/Utility/OpenAIClientUtilities.cs
64lines · modecode
| 1 | using System; |
| 2 | using System.ClientModel; |
| 3 | using System.ClientModel.Primitives; |
| 4 | |
| 5 | namespace OpenAI; |
| 6 | |
| 7 | internal static class OpenAIClientUtilities |
| 8 | { |
| 9 | public const string OpenAIV1Endpoint = "https://api.openai.com/v1"; |
| 10 | |
| 11 | private const string AuthorizationHeader = "Authorization"; |
| 12 | private const string AuthorizationApiKeyPrefix = "Bearer"; |
| 13 | |
| 14 | private const string OpenAIOrganizationHeaderName = "OpenAI-Organization"; |
| 15 | private const string OpenAIProjectHeaderName = "OpenAI-Project"; |
| 16 | private const string UserAgentHeaderName = "User-Agent"; |
| 17 | |
| 18 | public static AuthenticationPolicy CreateApiKeyAuthenticationPolicy(ApiKeyCredential credential) |
| 19 | { |
| 20 | Argument.AssertNotNull(credential, nameof(credential)); |
| 21 | return ApiKeyAuthenticationPolicy.CreateHeaderApiKeyPolicy(credential, AuthorizationHeader, AuthorizationApiKeyPrefix); |
| 22 | } |
| 23 | |
| 24 | public static ClientPipeline CreatePipeline( |
| 25 | AuthenticationPolicy authenticationPolicy, |
| 26 | ClientPipelineOptions options, |
| 27 | string userAgentApplicationId, |
| 28 | string organizationId, |
| 29 | string projectId) |
| 30 | { |
| 31 | return ClientPipeline.Create( |
| 32 | options: options, |
| 33 | perCallPolicies: [CreateAddCustomHeadersPolicy(userAgentApplicationId, organizationId, projectId)], |
| 34 | perTryPolicies: [authenticationPolicy], |
| 35 | beforeTransportPolicies: []); |
| 36 | } |
| 37 | |
| 38 | public static Uri GetEndpoint(Uri endpoint) |
| 39 | { |
| 40 | return endpoint ?? new Uri(OpenAIV1Endpoint); |
| 41 | } |
| 42 | |
| 43 | private static PipelinePolicy CreateAddCustomHeadersPolicy(string userAgentApplicationId, string organizationId, string projectId) |
| 44 | { |
| 45 | TelemetryDetails telemetryDetails = new(typeof(OpenAIClientUtilities).Assembly, userAgentApplicationId); |
| 46 | return new GenericActionPipelinePolicy((message) => |
| 47 | { |
| 48 | if (message?.Request?.Headers?.TryGetValue(UserAgentHeaderName, out string _) == false) |
| 49 | { |
| 50 | message.Request.Headers.Set(UserAgentHeaderName, telemetryDetails.ToString()); |
| 51 | } |
| 52 | |
| 53 | if (!string.IsNullOrEmpty(organizationId)) |
| 54 | { |
| 55 | message.Request.Headers.Set(OpenAIOrganizationHeaderName, organizationId); |
| 56 | } |
| 57 | |
| 58 | if (!string.IsNullOrEmpty(projectId)) |
| 59 | { |
| 60 | message.Request.Headers.Set(OpenAIProjectHeaderName, projectId); |
| 61 | } |
| 62 | }); |
| 63 | } |
| 64 | } |