-
Notifications
You must be signed in to change notification settings - Fork 287
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
Open
claudiogodoy99
wants to merge
9
commits into
openai:main
Choose a base branch
from
claudiogodoy99:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+280
−0
Open
Changes from all commits
Commits
Show all changes
9 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 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,73 @@ | ||
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"))) | ||
); | ||
builder.Services.AddScoped<ChatHttpHandler>(); | ||
|
||
|
||
var app = builder.Build(); | ||
|
||
// Configure the HTTP request pipeline. | ||
if (app.Environment.IsDevelopment()) | ||
{ | ||
app.UseSwagger(); | ||
app.UseSwaggerUI(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
var chatHandler = app.Services.GetRequiredService<ChatHttpHandler>(); | ||
|
||
app.MapPost("/chat/complete", chatHandler.HandleChatRequest); | ||
|
||
app.Run(); | ||
|
||
public class ChatHttpHandler | ||
{ | ||
private readonly ChatClient _client; | ||
private readonly ILogger<ChatHttpHandler> _logger; | ||
|
||
// Chat completion endpoint using injected ChatClient client | ||
public ChatHttpHandler(ChatClient client, ILogger<ChatHttpHandler> logger) | ||
{ | ||
_client = client; | ||
_logger = logger; | ||
} | ||
|
||
public async Task<ChatResponse> HandleChatRequest(ChatRequest request) | ||
{ | ||
_logger.LogInformation("Handling chat request: {Message}", request.Message); | ||
var completion = await _client.CompleteChatAsync(request.Message); | ||
return new ChatResponse(completion.Value.Content[0].Text); | ||
} | ||
} | ||
|
||
public class ChatRequest | ||
{ | ||
public string Message { get; set; } | ||
|
||
public ChatRequest(string message) | ||
{ | ||
Message = message; | ||
} | ||
} | ||
|
||
public class ChatResponse | ||
{ | ||
public string Response { get; set; } | ||
|
||
public ChatResponse(string response) | ||
{ | ||
Response = response; | ||
} | ||
} |
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,125 @@ | ||
# 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. | ||
|
||
## 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):** | ||
|
||
```powershell | ||
$env:OPENAI_API_KEY = "your-api-key-here" | ||
``` | ||
|
||
**Configuration (appsettings.json):** | ||
|
||
```json | ||
{ | ||
"OpenAI": { | ||
"Model": "gpt-4o-mini", | ||
"ApiKey": "your-api-key-here" | ||
} | ||
} | ||
``` | ||
|
||
2. **Install dependencies:** | ||
|
||
```powershell | ||
dotnet restore | ||
``` | ||
|
||
3. **Run the application:** | ||
|
||
```powershell | ||
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 PowerShell | ||
|
||
**Chat Completion:** | ||
|
||
```powershell | ||
Invoke-RestMethod -Uri "https://localhost:5000/chat/complete" ` | ||
-Method POST ` | ||
-ContentType "application/json" ` | ||
-Body '{"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 | ||
- **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. | ||
|
||
## Additional Resources | ||
|
||
- [Tutorial: Create a minimal API with ASP.NET Core](https://learn.microsoft.com/aspnet/core/tutorials/min-web-api) | ||
- [.NET dependency injection](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection) | ||
- [Logging in C# and .NET](https://learn.microsoft.com/dotnet/core/extensions/logging) |
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,18 @@ | ||||||||||||||
{ | ||||||||||||||
"Logging": { | ||||||||||||||
"LogLevel": { | ||||||||||||||
"Default": "Information", | ||||||||||||||
"Microsoft.AspNetCore": "Warning" | ||||||||||||||
} | ||||||||||||||
}, | ||||||||||||||
"AllowedHosts": "*", | ||||||||||||||
"OpenAI": | ||||||||||||||
{ | ||||||||||||||
<<<<<<< HEAD | ||||||||||||||
"Model": "gpt-4.1-mini", | ||||||||||||||
======= | ||||||||||||||
"Model": "gpt-4.1", | ||||||||||||||
>>>>>>> 2ef2c53 (chore: remove api secret and unused records) | ||||||||||||||
Comment on lines
+11
to
+15
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Looks like some conflict markers got left in. I believe the latest change was to move to |
||||||||||||||
"ApiKey": "" | ||||||||||||||
} | ||||||||||||||
} |
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"> | ||||||
|
||||||
<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" /> | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
<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.