Skip to content

Commit

Permalink
Add UseConfiguration method (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcominerva authored Jun 5, 2023
2 parents 287ce5b + dff2ff1 commit f755eb1
Show file tree
Hide file tree
Showing 10 changed files with 61 additions and 18 deletions.
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ If necessary, it is possibile to provide a custom Cache by implementing the [ICh

We can also set ChatGPT parameters for chat completion at startup. Check the [official documentation](https://platform.openai.com/docs/api-reference/chat/create) for the list of available parameters and their meaning.

## Configuration using an external source
### Configuration using an external source

The configuration can be automatically read from [IConfiguration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iconfiguration), using for example a _ChatGPT_ section in the _appsettings.json_ file:

Expand Down Expand Up @@ -130,7 +130,7 @@ And then use the corresponding overload of che **AddChatGpt** method:
// Adds ChatGPT service using settings from IConfiguration.
builder.Services.AddChatGpt(builder.Configuration);

## Configuring ChatGptNet dinamically
### Configuring ChatGptNet dinamically

The **AddChatGpt** method has also an overload that accepts an [IServiceProvider](https://learn.microsoft.com/dotnet/api/system.iserviceprovider) as argument. It can be used, for example, if we're in a Web API and we need to support scenarios in which every user has a different API Key that can be retrieved accessing a database via Dependency Injection:

Expand All @@ -144,6 +144,22 @@ The **AddChatGpt** method has also an overload that accepts an [IServiceProvider
options.UseOpenAI(apiKyey);
});

### Configuring ChatGptNet using both IConfiguration and code

In more complex scenarios, it is possible to configure **ChatGptNet** using both code and [IConfiguration](https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iconfiguration). This can be useful if we want to set a bunch of common properties, but at the same time we need some configuration logic. For example:

builder.Services.AddChatGpt((services, options) =>
{
// Configure common properties (message limit and expiration, default parameters, ecc.) using IConfiguration.
options.UseConfiguration(builder.Configuration);

var accountService = services.GetRequiredService<IAccountService>();

// Dynamically gets the API Key from the service.
var apiKey = "..."

options.UseOpenAI(apiKyey);
});

## Usage

Expand Down
2 changes: 1 addition & 1 deletion samples/ChatGptApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

// Adds ChatGPT service with hard-coded settings.
// Adds ChatGPT service and configure options via code.
//builder.Services.AddChatGpt(options =>
//{
// // OpenAI.
Expand Down
1 change: 1 addition & 0 deletions samples/ChatGptBlazor.Wasm/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

// Adds ChatGPT service and configure options via code.
builder.Services.AddChatGpt(options =>
{
// OpenAI.
Expand Down
19 changes: 14 additions & 5 deletions samples/ChatGptConsole/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ static void ConfigureServices(HostBuilderContext context, IServiceCollection ser
{
services.AddSingleton<Application>();

// Adds ChatGPT service with hard-coded settings.
// Adds ChatGPT service using settings from IConfiguration.
services.AddChatGpt(context.Configuration)
//.WithCache<LocalMessageCache>() // Uncomment this line to use a custom cache implementation instead of the default MemoryCache.
;

// Adds ChatGPT service and configure options via code.
//services.AddChatGpt(options =>
//{
// // OpenAI.
Expand All @@ -28,10 +33,14 @@ static void ConfigureServices(HostBuilderContext context, IServiceCollection ser
// options.MessageExpiration = TimeSpan.FromMinutes(5); // Default: 1 hour
//});

// Adds ChatGPT service using settings from IConfiguration.
services.AddChatGpt(context.Configuration)
//.WithCache<LocalMessageCache>() // Uncomment this line to use a custom cache implementation instead of the default MemoryCache.
;
// Adds ChatGPT service using settings from IConfiguration and code.
//services.AddChatGpt(options =>
//{
// options.UseConfiguration(context.Configuration);

// options.UseOpenAI(apiKey: "");
// options.DefaultModel = OpenAIChatGptModels.Gpt35Turbo;
//});
}

public class LocalMessageCache : IChatGptCache
Expand Down
2 changes: 1 addition & 1 deletion samples/ChatGptStreamConsole/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ static void ConfigureServices(HostBuilderContext context, IServiceCollection ser
{
services.AddSingleton<Application>();

// Adds ChatGPT service with hard-coded settings.
// Adds ChatGPT service and configure options via code.
//services.AddChatGpt(options =>
//{
// // OpenAI.
Expand Down
4 changes: 2 additions & 2 deletions src/ChatGptNet/ChatGptOptionsBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public class ChatGptOptionsBuilder
/// Gets or sets the default parameters for chat completion.
/// </summary>
/// <see cref="ChatGptParameters"/>
public ChatGptParameters DefaultParameters { get; } = new();
public ChatGptParameters? DefaultParameters { get; set; } = new();

/// <summary>
/// Gets or sets the user identification for chat completion, which can help OpenAI to monitor and detect abuse.
Expand All @@ -60,7 +60,7 @@ internal ChatGptOptions Build()
{
MessageLimit = MessageLimit,
DefaultModel = DefaultModel,
DefaultParameters = DefaultParameters,
DefaultParameters = DefaultParameters ?? new(),
MessageExpiration = MessageExpiration,
ThrowExceptionOnError = ThrowExceptionOnError,
ServiceConfiguration = ServiceConfiguration,
Expand Down
21 changes: 21 additions & 0 deletions src/ChatGptNet/ChatGptOptionsBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using ChatGptNet.ServiceConfigurations;
using Microsoft.Extensions.Configuration;

namespace ChatGptNet;

Expand Down Expand Up @@ -62,4 +63,24 @@ public static ChatGptOptionsBuilder UseAzure(this ChatGptOptionsBuilder builder,

return builder;
}

/// <summary>
/// Configures the <see cref="ChatGptClient"/> reading configuration from the specified <see cref="IConfiguration"/> source.
/// </summary>
/// <param name="builder">The <see cref="ChatGptOptionsBuilder"/> object to configure.</param>
/// <param name="configuration">The <see cref="IConfiguration"/> being bound.</param>
/// <param name="sectionName">The name of the configuration section that holds ChatGPT settings (default: ChatGPT).</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
/// <seealso cref="ChatGptOptionsBuilder"/>
/// <seealso cref="IConfiguration"/>
public static ChatGptOptionsBuilder UseConfiguration(this ChatGptOptionsBuilder builder, IConfiguration configuration, string sectionName = "ChatGPT")
{
var configurationSection = configuration.GetSection(sectionName);
configurationSection.Bind(builder);

// Creates the service configuration (OpenAI or Azure) according to the configuration settings.
builder.ServiceConfiguration = ChatGptServiceConfiguration.Create(configurationSection);

return builder;
}
}
6 changes: 1 addition & 5 deletions src/ChatGptNet/ChatGptServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ public static IChatGptBuilder AddChatGpt(this IServiceCollection services, IConf
ArgumentNullException.ThrowIfNull(configuration);

var options = new ChatGptOptionsBuilder();
var configurationSection = configuration.GetSection(sectionName);
configurationSection.Bind(options);

// Creates the service configuration (OpenAI or Azure) according to the configuration settings.
options.ServiceConfiguration = ChatGptServiceConfiguration.Create(configurationSection);
options.UseConfiguration(configuration, sectionName);

SetMissingDefaults(options);
services.AddSingleton(options.Build());
Expand Down
2 changes: 1 addition & 1 deletion src/ChatGptNet/Models/ChatGptResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace ChatGptNet.Models;
public class ChatGptResponse
{
/// <summary>
/// Gets or sets the Id of the response
/// Gets or sets the Id of the response.
/// </summary>
public string Id { get; set; } = string.Empty;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public OpenAIChatGptServiceConfiguration(IConfiguration configuration)
}

/// <inheritdoc />
public override Uri GetServiceEndpoint(string? modelName) => new("https://api.openai.com/v1/chat/completions");
public override Uri GetServiceEndpoint(string? _) => new("https://api.openai.com/v1/chat/completions");

/// <inheritdoc />
public override IDictionary<string, string?> GetRequestHeaders()
Expand Down

0 comments on commit f755eb1

Please sign in to comment.