Skip to content

Commit

Permalink
Fixed WebAPI
Browse files Browse the repository at this point in the history
Upgraded to .NET8.0
Fixed logging (removed Console replaced with Ilogger)
Fixed warnings (Null Strings, etc).

The application now returns data from the back-end chat services.
  • Loading branch information
scotmcc committed Dec 18, 2023
1 parent 7139281 commit 2abc2ec
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 81 deletions.
52 changes: 27 additions & 25 deletions LLama.WebAPI/LLama.WebAPI.csproj
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="..\LLama\LLamaSharp.Runtime.targets" />
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Validation" Version="17.8.8" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\LLama\LLamaSharp.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="Properties\launchSettings.json">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<Import Project="..\LLama\LLamaSharp.Runtime.targets" />
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Validation" Version="17.8.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\LLama\LLamaSharp.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="Properties\launchSettings.json">
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
</Project>
8 changes: 4 additions & 4 deletions LLama.WebAPI/Models/SendMessageInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

public class SendMessageInput
{
public string Text { get; set; }
public string Text { get; set; } = "";
}

public class HistoryInput
{
public List<HistoryItem> Messages { get; set; }
public List<HistoryItem> Messages { get; set; } = [];
public class HistoryItem
{
public string Role { get; set; }
public string Content { get; set; }
public string Role { get; set; } = "User";
public string Content { get; set; } = "";
}
}
60 changes: 32 additions & 28 deletions LLama.WebAPI/Program.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
using LLama.WebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<StatefulChatService>();
builder.Services.AddScoped<StatelessChatService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
using LLama.WebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddSingleton<StatefulChatService>();
builder.Services.AddScoped<StatelessChatService>();

var app = builder.Build();
app.UseRouting();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
_ = endpoints.MapControllers();
});

app.Run();
27 changes: 12 additions & 15 deletions LLama.WebAPI/Services/StatefulChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,22 @@ public class StatefulChatService : IDisposable
{
private readonly ChatSession _session;
private readonly LLamaContext _context;
private readonly ILogger<StatefulChatService> _logger;
private bool _continue = false;

private const string SystemPrompt = "Transcript of a dialog, where the User interacts with an Assistant. Assistant is helpful, kind, honest, good at writing, and never fails to answer the User's requests immediately and with precision.";

public StatefulChatService(IConfiguration configuration)
public StatefulChatService(IConfiguration configuration, ILogger<StatefulChatService> logger)
{
var @params = new Common.ModelParams(configuration["ModelPath"])
var @params = new Common.ModelParams(configuration["ModelPath"]!)
{
ContextSize = 512,
};

// todo: share weights from a central service
using var weights = LLamaWeights.LoadFromFile(@params);

_logger = logger;
_context = new LLamaContext(weights, @params);

_session = new ChatSession(new InteractiveExecutor(_context));
Expand All @@ -36,16 +38,13 @@ public void Dispose()

public async Task<string> Send(SendMessageInput input)
{

if (!_continue)
{
Console.Write(SystemPrompt);
_logger.LogInformation("Prompt: {text}", SystemPrompt);
_continue = true;
}

Console.ForegroundColor = ConsoleColor.Green;
Console.Write(input.Text);

Console.ForegroundColor = ConsoleColor.White;
_logger.LogInformation("Input: {text}", input.Text);
var outputs = _session.ChatAsync(
new Common.ChatHistory.Message(Common.AuthorRole.User, input.Text),
new Common.InferenceParams()
Expand All @@ -57,7 +56,7 @@ public async Task<string> Send(SendMessageInput input)
var result = "";
await foreach (var output in outputs)
{
Console.Write(output);
_logger.LogInformation("Message: {output}", output);
result += output;
}

Expand All @@ -68,16 +67,14 @@ public async IAsyncEnumerable<string> SendStream(SendMessageInput input)
{
if (!_continue)
{
Console.Write(SystemPrompt);
_logger.LogInformation(SystemPrompt);
_continue = true;
}

Console.ForegroundColor = ConsoleColor.Green;
Console.Write(input.Text);
_logger.LogInformation(input.Text);

Console.ForegroundColor = ConsoleColor.White;
var outputs = _session.ChatAsync(
new Common.ChatHistory.Message(Common.AuthorRole.User, input.Text)
new Common.ChatHistory.Message(Common.AuthorRole.User, input.Text!)
, new Common.InferenceParams()
{
RepeatPenalty = 1.0f,
Expand All @@ -86,7 +83,7 @@ public async IAsyncEnumerable<string> SendStream(SendMessageInput input)

await foreach (var output in outputs)
{
Console.Write(output);
_logger.LogInformation(output);
yield return output;
}
}
Expand Down
2 changes: 1 addition & 1 deletion LLama.WebAPI/Services/StatelessChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class StatelessChatService

public StatelessChatService(IConfiguration configuration)
{
var @params = new Common.ModelParams(configuration["ModelPath"])
var @params = new Common.ModelParams(configuration["ModelPath"]!)
{
ContextSize = 512,
};
Expand Down
16 changes: 8 additions & 8 deletions LLama.WebAPI/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

0 comments on commit 2abc2ec

Please sign in to comment.