-
Notifications
You must be signed in to change notification settings - Fork 342
Add ASP.NET Core example and update README #499
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4445b98
chore: add ASP.NET Core example and update README
claudiogodoy99 0f85f5e
Update examples/ASP.NET Core/README.md
claudiogodoy99 8f28bf8
Update examples/ASP.NET Core/README.md
claudiogodoy99 049302d
fix: missing table content for new paragraph
claudiogodoy99 312a4ac
fix: rename structure new example project
claudiogodoy99 f533118
chore: refactor example README.md to follow Windows first approach
claudiogodoy99 b1edf20
docs: add Additional resources paragraph on README.md
claudiogodoy99 d5b3d70
chore: remove api secret and unused records
claudiogodoy99 03172e4
remove record from new example
claudiogodoy99 d4a6c96
Update examples/aspnet-core/appsettings.json
claudiogodoy99 b710a0c
Update examples/aspnet-core/aspnet-core.csproj
claudiogodoy99 c488445
chore: fix CI by excluding aspnet-core subdirectory
claudiogodoy99 a35be79
chore: update README to use ChatClient instead of OpenAIClient
claudiogodoy99 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||
jsquire marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Visual Studio Version 17 | ||
| VisualStudioVersion = 17.5.2.0 | ||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "client-di", "client-di.csproj", "{F3F2E48A-807D-4AC2-064F-2417457154CA}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {F3F2E48A-807D-4AC2-064F-2417457154CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {F3F2E48A-807D-4AC2-064F-2417457154CA}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {F3F2E48A-807D-4AC2-064F-2417457154CA}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {F3F2E48A-807D-4AC2-064F-2417457154CA}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(SolutionProperties) = preSolution | ||
| HideSolutionNode = FALSE | ||
| EndGlobalSection | ||
| GlobalSection(ExtensibilityGlobals) = postSolution | ||
| SolutionGuid = {33398145-928F-4A73-A7AE-4B3ED3CE96C2} | ||
| EndGlobalSection | ||
| EndGlobal | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| using System.ClientModel; | ||
| using OpenAI.Chat; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| // Add services to the container. | ||
| builder.Services.AddEndpointsApiExplorer(); | ||
| builder.Services.AddSwaggerGen(); | ||
|
|
||
| builder.Services.AddSingleton<ChatClient>(serviceProvider => new ChatClient(builder.Configuration["OpenAI:Model"], | ||
| new ApiKeyCredential(builder.Configuration["OpenAI:ApiKey"] | ||
| ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY") | ||
| ?? throw new InvalidOperationException("OpenAI API key not found"))) | ||
| ); | ||
|
|
||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| // Configure the HTTP request pipeline. | ||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
| } | ||
|
|
||
| app.UseHttpsRedirection(); | ||
|
|
||
| // Chat completion endpoint using injected ChatClient client | ||
| app.MapPost("/chat/complete", async (ChatRequest request, ChatClient client) => | ||
| { | ||
| var completion = await client.CompleteChatAsync(request.Message); | ||
|
|
||
| return new ChatResponse(completion.Value.Content[0].Text); | ||
| }); | ||
|
|
||
| app.Run(); | ||
|
|
||
| record ChatRequest(string Message); | ||
jsquire marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| record ChatResponse(string Response); | ||
| record EmbeddingRequest(string Text); | ||
| record EmbeddingResponse(float[] Vector); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| # OpenAI ASP.NET Core Example | ||
|
|
||
| This example demonstrates how to use the OpenAI .NET client library with ASP.NET Core's dependency injection container, registering a ChatClient as a singleton for optimal performance and resource usage. | ||
claudiogodoy99 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
jsquire marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## Features | ||
|
|
||
| - **Singleton Registration**: ChatClient registered as singleton in DI container | ||
| - **Thread-Safe**: Demonstrates concurrent usage for chat completion endpoints | ||
| - **Configurable Model**: Model selection via configuration (appsettings.json) | ||
| - **Modern ASP.NET Core**: Uses minimal APIs with async/await patterns | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - .NET 8.0 or later | ||
| - OpenAI API key | ||
|
|
||
| ## Setup | ||
|
|
||
| 1. **Set your OpenAI API key** using one of these methods: | ||
|
|
||
| **Environment Variable (Recommended):** | ||
jsquire marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| ```bash | ||
| export OPENAI_API_KEY="your-api-key-here" | ||
| ``` | ||
|
|
||
| **Configuration (appsettings.json):** | ||
|
|
||
| ```json | ||
| { | ||
| "OpenAI": { | ||
| "Model": "gpt-4o-mini", | ||
| "ApiKey": "your-api-key-here" | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| 2. **Install dependencies:** | ||
|
|
||
| ```bash | ||
| dotnet restore | ||
| ``` | ||
|
|
||
| 3. **Run the application:** | ||
|
|
||
| ```bash | ||
| dotnet run | ||
| ``` | ||
|
|
||
| ## API Endpoints | ||
|
|
||
| ### Chat Completion | ||
|
|
||
| - **POST** `/chat/complete` | ||
| - **Request Body:** | ||
|
|
||
| ```json | ||
| { | ||
| "message": "Hello, how are you?" | ||
| } | ||
| ``` | ||
|
|
||
| - **Response:** | ||
|
|
||
| ```json | ||
| { | ||
| "response": "I'm doing well, thank you for asking! How can I help you today?" | ||
| } | ||
| ``` | ||
|
|
||
| ## Testing with cURL | ||
|
|
||
| **Chat Completion:** | ||
|
|
||
| ```bash | ||
| curl -X POST "https://localhost:7071/chat/complete" \ | ||
jsquire marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| -H "Content-Type: application/json" \ | ||
| -d '{"message": "What is the capital of France?"}' | ||
| ``` | ||
|
|
||
| ## Key Implementation Details | ||
|
|
||
| ### Singleton Registration | ||
|
|
||
| ```csharp | ||
| builder.Services.AddSingleton<ChatClient>(serviceProvider => new ChatClient( | ||
| builder.Configuration["OpenAI:Model"], | ||
| new ApiKeyCredential(builder.Configuration["OpenAI:ApiKey"] | ||
| ?? Environment.GetEnvironmentVariable("OPENAI_API_KEY") | ||
| ?? throw new InvalidOperationException("OpenAI API key not found"))) | ||
| ); | ||
| ``` | ||
|
|
||
| ### Dependency Injection Usage | ||
|
|
||
| ```csharp | ||
| app.MapPost("/chat/complete", async (ChatRequest request, ChatClient client) => | ||
| { | ||
| var completion = await client.CompleteChatAsync(request.Message); | ||
|
|
||
| return new ChatResponse(completion.Value.Content[0].Text); | ||
| }); | ||
| ``` | ||
|
|
||
| ## Why Singleton? | ||
|
|
||
| - **Thread-Safe**: ChatClient is thread-safe and can handle concurrent requests | ||
claudiogodoy99 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| - **Resource Efficient**: Reuses HTTP connections and avoids creating multiple instances | ||
| - **Performance**: Reduces object allocation overhead | ||
| - **Stateless**: Clients don't maintain per-request state | ||
|
|
||
| ## Swagger UI | ||
|
|
||
| When running in development mode, you can access the Swagger UI at: | ||
|
|
||
| - `https://localhost:7071/swagger` | ||
|
|
||
| This provides an interactive interface to test the API endpoints. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "OpenAI": | ||
| { | ||
| "Model": "gpt-4.1-mini", | ||
| "ApiKey": "YOUR_API_KEY" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
jsquire marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <RootNamespace>ASP.NET_Core</RootNamespace> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="OpenAI" Version="2.1.0" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.