├── .gitignore ├── RagBasics.sln └── RagBasics ├── EmbeddingGenerator ├── IEmbeddingGenerator.cs ├── OllamaEmbeddingGenerator.cs └── OllamaEmbeddingResponse.cs ├── Models ├── AddTextRequest.cs └── OllamaCompletionResponse.cs ├── Program.cs ├── Properties └── launchSettings.json ├── RagBasics.csproj ├── RagBasics.http ├── Repository ├── TextContext.cs └── TextRepository.cs ├── Services └── RagService.cs ├── appsettings.Development.json └── appsettings.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | # but not Directory.Build.rsp, as it configures directory-level build defaults 86 | !Directory.Build.rsp 87 | *.sbr 88 | *.tlb 89 | *.tli 90 | *.tlh 91 | *.tmp 92 | *.tmp_proj 93 | *_wpftmp.csproj 94 | *.log 95 | *.tlog 96 | *.vspscc 97 | *.vssscc 98 | .builds 99 | *.pidb 100 | *.svclog 101 | *.scc 102 | 103 | # Chutzpah Test files 104 | _Chutzpah* 105 | 106 | # Visual C++ cache files 107 | ipch/ 108 | *.aps 109 | *.ncb 110 | *.opendb 111 | *.opensdf 112 | *.sdf 113 | *.cachefile 114 | *.VC.db 115 | *.VC.VC.opendb 116 | 117 | # Visual Studio profiler 118 | *.psess 119 | *.vsp 120 | *.vspx 121 | *.sap 122 | 123 | # Visual Studio Trace Files 124 | *.e2e 125 | 126 | # TFS 2012 Local Workspace 127 | $tf/ 128 | 129 | # Guidance Automation Toolkit 130 | *.gpState 131 | 132 | # ReSharper is a .NET coding add-in 133 | _ReSharper*/ 134 | *.[Rr]e[Ss]harper 135 | *.DotSettings.user 136 | 137 | # TeamCity is a build add-in 138 | _TeamCity* 139 | 140 | # DotCover is a Code Coverage Tool 141 | *.dotCover 142 | 143 | # AxoCover is a Code Coverage Tool 144 | .axoCover/* 145 | !.axoCover/settings.json 146 | 147 | # Coverlet is a free, cross platform Code Coverage Tool 148 | coverage*.json 149 | coverage*.xml 150 | coverage*.info 151 | 152 | # Visual Studio code coverage results 153 | *.coverage 154 | *.coveragexml 155 | 156 | # NCrunch 157 | _NCrunch_* 158 | .*crunch*.local.xml 159 | nCrunchTemp_* 160 | 161 | # MightyMoose 162 | *.mm.* 163 | AutoTest.Net/ 164 | 165 | # Web workbench (sass) 166 | .sass-cache/ 167 | 168 | # Installshield output folder 169 | [Ee]xpress/ 170 | 171 | # DocProject is a documentation generator add-in 172 | DocProject/buildhelp/ 173 | DocProject/Help/*.HxT 174 | DocProject/Help/*.HxC 175 | DocProject/Help/*.hhc 176 | DocProject/Help/*.hhk 177 | DocProject/Help/*.hhp 178 | DocProject/Help/Html2 179 | DocProject/Help/html 180 | 181 | # Click-Once directory 182 | publish/ 183 | 184 | # Publish Web Output 185 | *.[Pp]ublish.xml 186 | *.azurePubxml 187 | # Note: Comment the next line if you want to checkin your web deploy settings, 188 | # but database connection strings (with potential passwords) will be unencrypted 189 | *.pubxml 190 | *.publishproj 191 | 192 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 193 | # checkin your Azure Web App publish settings, but sensitive information contained 194 | # in these scripts will be unencrypted 195 | PublishScripts/ 196 | 197 | # NuGet Packages 198 | *.nupkg 199 | # NuGet Symbol Packages 200 | *.snupkg 201 | # The packages folder can be ignored because of Package Restore 202 | **/[Pp]ackages/* 203 | # except build/, which is used as an MSBuild target. 204 | !**/[Pp]ackages/build/ 205 | # Uncomment if necessary however generally it will be regenerated when needed 206 | #!**/[Pp]ackages/repositories.config 207 | # NuGet v3's project.json files produces more ignorable files 208 | *.nuget.props 209 | *.nuget.targets 210 | 211 | # Microsoft Azure Build Output 212 | csx/ 213 | *.build.csdef 214 | 215 | # Microsoft Azure Emulator 216 | ecf/ 217 | rcf/ 218 | 219 | # Windows Store app package directories and files 220 | AppPackages/ 221 | BundleArtifacts/ 222 | Package.StoreAssociation.xml 223 | _pkginfo.txt 224 | *.appx 225 | *.appxbundle 226 | *.appxupload 227 | 228 | # Visual Studio cache files 229 | # files ending in .cache can be ignored 230 | *.[Cc]ache 231 | # but keep track of directories ending in .cache 232 | !?*.[Cc]ache/ 233 | 234 | # Others 235 | ClientBin/ 236 | ~$* 237 | *~ 238 | *.dbmdl 239 | *.dbproj.schemaview 240 | *.jfm 241 | *.pfx 242 | *.publishsettings 243 | orleans.codegen.cs 244 | 245 | # Including strong name files can present a security risk 246 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 247 | #*.snk 248 | 249 | # Since there are multiple workflows, uncomment next line to ignore bower_components 250 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 251 | #bower_components/ 252 | 253 | # RIA/Silverlight projects 254 | Generated_Code/ 255 | 256 | # Backup & report files from converting an old project file 257 | # to a newer Visual Studio version. Backup files are not needed, 258 | # because we have git ;-) 259 | _UpgradeReport_Files/ 260 | Backup*/ 261 | UpgradeLog*.XML 262 | UpgradeLog*.htm 263 | ServiceFabricBackup/ 264 | *.rptproj.bak 265 | 266 | # SQL Server files 267 | *.mdf 268 | *.ldf 269 | *.ndf 270 | 271 | # Business Intelligence projects 272 | *.rdl.data 273 | *.bim.layout 274 | *.bim_*.settings 275 | *.rptproj.rsuser 276 | *- [Bb]ackup.rdl 277 | *- [Bb]ackup ([0-9]).rdl 278 | *- [Bb]ackup ([0-9][0-9]).rdl 279 | 280 | # Microsoft Fakes 281 | FakesAssemblies/ 282 | 283 | # GhostDoc plugin setting file 284 | *.GhostDoc.xml 285 | 286 | # Node.js Tools for Visual Studio 287 | .ntvs_analysis.dat 288 | node_modules/ 289 | 290 | # Visual Studio 6 build log 291 | *.plg 292 | 293 | # Visual Studio 6 workspace options file 294 | *.opt 295 | 296 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 297 | *.vbw 298 | 299 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 300 | *.vbp 301 | 302 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 303 | *.dsw 304 | *.dsp 305 | 306 | # Visual Studio 6 technical files 307 | *.ncb 308 | *.aps 309 | 310 | # Visual Studio LightSwitch build output 311 | **/*.HTMLClient/GeneratedArtifacts 312 | **/*.DesktopClient/GeneratedArtifacts 313 | **/*.DesktopClient/ModelManifest.xml 314 | **/*.Server/GeneratedArtifacts 315 | **/*.Server/ModelManifest.xml 316 | _Pvt_Extensions 317 | 318 | # Paket dependency manager 319 | .paket/paket.exe 320 | paket-files/ 321 | 322 | # FAKE - F# Make 323 | .fake/ 324 | 325 | # CodeRush personal settings 326 | .cr/personal 327 | 328 | # Python Tools for Visual Studio (PTVS) 329 | __pycache__/ 330 | *.pyc 331 | 332 | # Cake - Uncomment if you are using it 333 | # tools/** 334 | # !tools/packages.config 335 | 336 | # Tabs Studio 337 | *.tss 338 | 339 | # Telerik's JustMock configuration file 340 | *.jmconfig 341 | 342 | # BizTalk build output 343 | *.btp.cs 344 | *.btm.cs 345 | *.odx.cs 346 | *.xsd.cs 347 | 348 | # OpenCover UI analysis results 349 | OpenCover/ 350 | 351 | # Azure Stream Analytics local run output 352 | ASALocalRun/ 353 | 354 | # MSBuild Binary and Structured Log 355 | *.binlog 356 | 357 | # NVidia Nsight GPU debugger configuration file 358 | *.nvuser 359 | 360 | # MFractors (Xamarin productivity tool) working folder 361 | .mfractor/ 362 | 363 | # Local History for Visual Studio 364 | .localhistory/ 365 | 366 | # Visual Studio History (VSHistory) files 367 | .vshistory/ 368 | 369 | # BeatPulse healthcheck temp database 370 | healthchecksdb 371 | 372 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 373 | MigrationBackup/ 374 | 375 | # Ionide (cross platform F# VS Code tools) working folder 376 | .ionide/ 377 | 378 | # Fody - auto-generated XML schema 379 | FodyWeavers.xsd 380 | 381 | # VS Code files for those working on multiple tools 382 | .vscode/* 383 | !.vscode/settings.json 384 | !.vscode/tasks.json 385 | !.vscode/launch.json 386 | !.vscode/extensions.json 387 | *.code-workspace 388 | 389 | # Local History for Visual Studio Code 390 | .history/ 391 | 392 | # Windows Installer files from build outputs 393 | *.cab 394 | *.msi 395 | *.msix 396 | *.msm 397 | *.msp 398 | 399 | # JetBrains Rider 400 | *.sln.iml 401 | -------------------------------------------------------------------------------- /RagBasics.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35707.178 d17.12 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RagBasics", "RagBasics\RagBasics.csproj", "{CE14C6AD-86FD-4A16-BC2F-6903FDB7DE6C}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {CE14C6AD-86FD-4A16-BC2F-6903FDB7DE6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {CE14C6AD-86FD-4A16-BC2F-6903FDB7DE6C}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {CE14C6AD-86FD-4A16-BC2F-6903FDB7DE6C}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {CE14C6AD-86FD-4A16-BC2F-6903FDB7DE6C}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /RagBasics/EmbeddingGenerator/IEmbeddingGenerator.cs: -------------------------------------------------------------------------------- 1 | namespace RagBasics.EmbeddingGenerator; 2 | 3 | public interface IEmbeddingGenerator 4 | { 5 | Task GenerateEmbeddingAsync(string text); 6 | } -------------------------------------------------------------------------------- /RagBasics/EmbeddingGenerator/OllamaEmbeddingGenerator.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using System.Text.Json; 3 | 4 | namespace RagBasics.EmbeddingGenerator; 5 | 6 | public class OllamaEmbeddingGenerator(Uri ollamaUrl, string modelId = "mistral") : IEmbeddingGenerator 7 | { 8 | private readonly HttpClient _httpClient = new(); 9 | private readonly Uri _ollamaUrl = ollamaUrl; 10 | private readonly string _modelId = modelId; 11 | 12 | public async Task GenerateEmbeddingAsync(string text) 13 | { 14 | var requestBody = new { model = _modelId, prompt = text }; 15 | 16 | var response = await _httpClient.PostAsync( 17 | new Uri(_ollamaUrl, "/api/embeddings"), 18 | new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")); 19 | 20 | if (!response.IsSuccessStatusCode) 21 | { 22 | throw new Exception($"Ollama API error: {await response.Content.ReadAsStringAsync()}"); 23 | } 24 | 25 | var responseJson = await response.Content.ReadAsStringAsync(); 26 | Console.WriteLine("Ollama Response: " + responseJson); 27 | 28 | var serializationOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; 29 | 30 | var embeddingResponse = JsonSerializer.Deserialize(responseJson, serializationOptions); 31 | 32 | if (embeddingResponse?.Embedding == null || embeddingResponse.Embedding.Length == 0) 33 | { 34 | throw new Exception("Failed to generate embedding."); 35 | } 36 | 37 | return embeddingResponse.Embedding; 38 | } 39 | } -------------------------------------------------------------------------------- /RagBasics/EmbeddingGenerator/OllamaEmbeddingResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace RagBasics.EmbeddingGenerator; 4 | 5 | public class OllamaEmbeddingResponse 6 | { 7 | [JsonPropertyName("embedding")] 8 | public float[] Embedding { get; set; } = []; 9 | } -------------------------------------------------------------------------------- /RagBasics/Models/AddTextRequest.cs: -------------------------------------------------------------------------------- 1 | namespace RagBasics.Models; 2 | 3 | public class AddTextRequest 4 | { 5 | public string Content { get; set; } = string.Empty; 6 | } -------------------------------------------------------------------------------- /RagBasics/Models/OllamaCompletionResponse.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace RagBasics.Models; 4 | 5 | public class OllamaCompletionResponse 6 | { 7 | [JsonPropertyName("response")] 8 | public string Response { get; set; } = string.Empty; 9 | 10 | [JsonPropertyName("context")] 11 | public List Context { get; set; } = []; 12 | } -------------------------------------------------------------------------------- /RagBasics/Program.cs: -------------------------------------------------------------------------------- 1 | using RagBasics.EmbeddingGenerator; 2 | using RagBasics.Models; 3 | using RagBasics.Repository; 4 | using RagBasics.Services; 5 | 6 | namespace RagBasics 7 | { 8 | public class Program 9 | { 10 | public static void Main(string[] args) 11 | { 12 | var builder = WebApplication.CreateBuilder(args); 13 | var configuration = builder.Configuration; 14 | 15 | // Load settings from appsettings.json 16 | var connectionString = configuration.GetConnectionString("PostgreSQL"); 17 | 18 | if (string.IsNullOrEmpty(connectionString)) 19 | { 20 | throw new InvalidOperationException("Required configuration settings are missing."); 21 | } 22 | 23 | // Register services 24 | builder.Services.AddSingleton(sp => 25 | new OllamaEmbeddingGenerator(new Uri("http://127.0.0.1:11434"), "mistral")); 26 | 27 | builder.Services.AddSingleton(sp => 28 | new TextRepository(connectionString, sp.GetRequiredService())); 29 | 30 | builder.Services.AddSingleton(sp => 31 | new RagService(sp.GetRequiredService(), new Uri("http://127.0.0.1:11434"), "mistral")); 32 | 33 | var app = builder.Build(); 34 | 35 | // Minimal API endpoints 36 | app.MapPost("/add-text", async (TextRepository textRepository, HttpContext context) => 37 | { 38 | var request = await context.Request.ReadFromJsonAsync(); 39 | if (string.IsNullOrWhiteSpace(request?.Content)) 40 | { 41 | return Results.BadRequest("Content is required."); 42 | } 43 | 44 | await textRepository.StoreTextAsync(request.Content); 45 | 46 | return Results.Ok("Text added successfully."); 47 | }); 48 | 49 | app.MapGet("/ask", async (RagService ragService, string query) => 50 | { 51 | if (string.IsNullOrWhiteSpace(query)) 52 | { 53 | return Results.BadRequest("Query parameter is required."); 54 | } 55 | 56 | var response = await ragService.GetAnswerAsync(query); 57 | 58 | return Results.Ok(new { query, response }); 59 | }); 60 | 61 | app.Run(); 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /RagBasics/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "profiles": { 4 | "http": { 5 | "commandName": "Project", 6 | "dotnetRunMessages": true, 7 | "launchBrowser": false, 8 | "applicationUrl": "http://localhost:5095", 9 | "environmentVariables": { 10 | "ASPNETCORE_ENVIRONMENT": "Development" 11 | } 12 | }, 13 | "https": { 14 | "commandName": "Project", 15 | "dotnetRunMessages": true, 16 | "launchBrowser": false, 17 | "applicationUrl": "https://localhost:7147;http://localhost:5095", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /RagBasics/RagBasics.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net9.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /RagBasics/RagBasics.http: -------------------------------------------------------------------------------- 1 | @RagBasics_HostAddress = http://localhost:5095 2 | 3 | GET {{RagBasics_HostAddress}}/weatherforecast/ 4 | Accept: application/json 5 | 6 | ### 7 | -------------------------------------------------------------------------------- /RagBasics/Repository/TextContext.cs: -------------------------------------------------------------------------------- 1 | namespace RagBasics.Repository; 2 | 3 | public class TextContext 4 | { 5 | public int Id { get; set; } 6 | public string Content { get; set; } = string.Empty; 7 | public float[] Embedding { get; set; } = []; 8 | } -------------------------------------------------------------------------------- /RagBasics/Repository/TextRepository.cs: -------------------------------------------------------------------------------- 1 | using System.Globalization; 2 | using Microsoft.Extensions.Hosting; 3 | using System.Text.RegularExpressions; 4 | using Npgsql; 5 | using RagBasics.EmbeddingGenerator; 6 | 7 | namespace RagBasics.Repository; 8 | 9 | public class TextRepository(string connectionString, IEmbeddingGenerator embeddingGenerator) 10 | { 11 | private readonly string _connectionString = connectionString; 12 | private readonly IEmbeddingGenerator _embeddingGenerator = embeddingGenerator; 13 | 14 | public async Task StoreTextAsync(string content) 15 | { 16 | var embedding = await _embeddingGenerator.GenerateEmbeddingAsync(content); 17 | 18 | using var conn = new NpgsqlConnection(_connectionString); 19 | 20 | await conn.OpenAsync(); 21 | 22 | string query = "INSERT INTO text_contexts (content, embedding) VALUES (@content, @embedding)"; 23 | using var cmd = new NpgsqlCommand(query, conn); 24 | cmd.Parameters.AddWithValue("content", content); 25 | cmd.Parameters.AddWithValue("embedding", embedding); 26 | 27 | await cmd.ExecuteNonQueryAsync(); 28 | } 29 | public async Task> RetrieveRelevantText(string query) 30 | { 31 | var queryEmbedding = await _embeddingGenerator.GenerateEmbeddingAsync(query); 32 | 33 | using var conn = new NpgsqlConnection(_connectionString); 34 | await conn.OpenAsync(); 35 | 36 | string querySql = @" 37 | SELECT content 38 | FROM text_contexts 39 | WHERE embedding <-> CAST(@queryEmbedding AS vector) > 0.7 40 | ORDER BY embedding <-> CAST(@queryEmbedding AS vector) 41 | LIMIT 5"; 42 | 43 | using var cmd = new NpgsqlCommand(querySql, conn); 44 | 45 | string embeddingString = $"[{string.Join(",", queryEmbedding.Select(v => v.ToString("G", CultureInfo.InvariantCulture)))}]"; 46 | cmd.Parameters.AddWithValue("queryEmbedding", embeddingString); 47 | 48 | using var reader = await cmd.ExecuteReaderAsync(); 49 | 50 | List results = new(); 51 | while (await reader.ReadAsync()) 52 | { 53 | results.Add(reader.GetString(0)); // Read "content" column 54 | } 55 | 56 | return results.Any() ? results : new List { "No relevant context found." }; 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /RagBasics/Services/RagService.cs: -------------------------------------------------------------------------------- 1 | using RagBasics.Models; 2 | using System.Text.Json; 3 | using System.Text; 4 | using RagBasics.Repository; 5 | 6 | namespace RagBasics.Services; 7 | 8 | public class RagService(TextRepository retriever, Uri ollamaUrl, string modelId = "mistral") 9 | { 10 | private readonly TextRepository _textRepository = retriever; 11 | private readonly HttpClient _httpClient = new(); 12 | private readonly Uri _ollamaUrl = ollamaUrl; 13 | private readonly string _modelId = modelId; 14 | 15 | public async Task GetAnswerAsync(string query) 16 | { 17 | // Retrieve multiple relevant texts 18 | List contexts = await _textRepository.RetrieveRelevantText(query); 19 | 20 | // Combine multiple contexts into one string 21 | string combinedContext = string.Join("\n\n---\n\n", contexts); 22 | 23 | // If no relevant context is found, return a strict message 24 | if (contexts.Count == 1 && contexts[0] == "No relevant context found.") 25 | { 26 | return new 27 | { 28 | Context = "No relevant data found in the database.", 29 | Response = "I don't know." 30 | }; 31 | } 32 | 33 | var requestBody = new 34 | { 35 | model = _modelId, 36 | prompt = $""" 37 | You are a strict AI assistant. You MUST answer ONLY using the provided context. 38 | If the answer is not in the context, respond with "I don't know. No relevant data found." 39 | 40 | Context: 41 | {combinedContext} 42 | 43 | Question: {query} 44 | """, 45 | stream = false 46 | }; 47 | 48 | var response = await _httpClient.PostAsync( 49 | new Uri(_ollamaUrl, "/api/generate"), 50 | new StringContent(JsonSerializer.Serialize(requestBody), Encoding.UTF8, "application/json")); 51 | 52 | if (!response.IsSuccessStatusCode) 53 | { 54 | return new 55 | { 56 | Context = combinedContext, 57 | Response = "Error: Unable to generate response." 58 | }; 59 | } 60 | 61 | var responseJson = await response.Content.ReadAsStringAsync(); 62 | var serializationOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; 63 | var completionResponse = JsonSerializer.Deserialize(responseJson, serializationOptions); 64 | 65 | return new 66 | { 67 | Context = combinedContext, 68 | Response = completionResponse?.Response ?? "I don't know. No relevant data found." 69 | }; 70 | } 71 | } -------------------------------------------------------------------------------- /RagBasics/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /RagBasics/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "ConnectionStrings": { 10 | "PostgreSQL": "Host=ep-empty-wind-a9yf7uso-pooler.gwc.azure.neon.tech;Database=neondb;Username=neondb_owner;Password=npg_B3MtwDOjS6RP;SSL Mode=Require;Trust Server Certificate=true" 11 | } 12 | } 13 | --------------------------------------------------------------------------------