# Luettelo "Lawyer GPT" -palveliasta blogillenne

<!--category-- AI, LLM, LLamaSharp, GGUF, C#, AI-Article, mostlylucid.blogllm -->
<datetime class="hidden">2025-11-12T22:45</datetime>

## Esitys

Welcome to Part 6! Olemme rakentaneet kokonaisen infrastruktuurin.[Osa 4](/blog/building-a-lawyer-gpt-for-your-blog-part4)Windows-klientti ),[Osa 5](/blog/building-a-lawyer-gpt-for-your-blog-part5)), sisällytykset ja vektoritutkimus[Osa 3](/blog/building-a-lawyer-gpt-for-your-blog-part3)), ja GPU:n käyttöönotto ([Osa 2](/blog/building-a-lawyer-gpt-for-your-blog-part2)). Nyt tulee jännittävä osa: paikallisen LLM:n integroiminen kirjoittamisen ehdotusten aikaansaamiseksi

> PANEE MERKILLE: Tämä on osa kokeilujani AI:n kanssa M SK1 avustettu laatiminen ) + omalla kääntämiselläni. Sama ääniMSC5 sama käytännönläheisyysMST6 vain nopeutetut sormetMSV7

Tämä on se paikka, jossa me viimeinkin teemme "AI" osan "AI-kirjanpitäjänä toimivasta avustajistaM SK3 työssäänMSC4 Teemme suuria kielimalleja paikallisesti omassa A:ssanne.

[TOC]

## Miksi paikallinen LLM?

Ennen kuin aiomme ottaa käyttöön OpenAI:n, meidän on ymmärrettävä, miksi käytämme mallia paikallisesti sen sijaan, että käytämme OpenAI-API:ta.

### Local vs API:n vertailu

| Aspekti | Paikallinen LLM | API MOpenAI, jne.
|--------|-----------|-------------------|
| **Yksityisyys** |
| **Kustannus** |
| **Latenssi** |
| **Yksinkertaistaminen** | ✅ Täysinvaltainen valvonta
| **Mallin valinta** |
| **Offline-järjestelmä** |
| **Järjestelmä** |

Kirjasta vastaavan avustajan osalta, yksityisyyden ja kustannusten valvontaa koskevat kysymyksetM SK1 emme halua blogin luonnoksien lähettämistä ulkopuolisille API:ille , ja per-token hinnoittelu lisää nopeasti päivittäisen kirjausvälineen hintaaMSC5

## LLM-integraatiovaihtoehdot C#

On useita tapoja käyttää LLM-järjestelmiä C#:

```mermaid
graph TB
    A[C# Application] --> B{Integration Method}

    B --> C[LLamaSharp]
    B --> D[ONNX Runtime]
    B --> E[TorchSharp]
    B --> F[HTTP API]

    C --> G[llama.cpp bindings]
    G --> H[GGUF Models]

    D --> I[ONNX Models]
    I --> J[Limited Model Support]

    E --> K[PyTorch Models]
    K --> L[Complex Setup]

    F --> M[External Process]
    M --> N[Ollama, LM Studio]

    class C recommended
    class G,H llamaSharp

    classDef recommended stroke:#333,stroke-width:4px
    classDef llamaSharp stroke:#333,stroke-width:2px
```

**Valinnani: LLamaSharp**

Miksi?

- Lamaan alkuperäiset C# sidokset
- Tuetaan GGUF-formattia (moderniaM SK1 kvantifioituja malleja)
- CUDA:n nopeuttaminen rakennettu-in
- Aktiivinen kehitys ja suuri yhteisö
- Sovelletaan Llamaa, Mistralia, Phia , GemmaaM SK3 ja muuta

## Ymmärrys mallimuodoista & Kvantointi

### GGUF-formatti

[GGUF](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) (~GPT~-~Generated Unified Format~)~ on standardi LLM:n tehokkaalle toiminnalle

```mermaid
graph LR
    A[Original Model<br/>Llama 2 7B<br/>~28GB float32] --> B[Quantization]

    B --> C[Q4_K_M<br/>~4.1GB<br/>4-bit]
    B --> D[Q5_K_M<br/>~4.8GB<br/>5-bit]
    B --> E[Q6_K<br/>~5.5GB<br/>6-bit]
    B --> F[Q8_0<br/>~7.2GB<br/>8-bit]

    C --> G[Fast, Lower Quality]
    D --> H[Balanced]
    E --> I[Higher Quality]
    F --> J[Near Original]

    class A original
    class C,D quantized
    class H recommended

    classDef original stroke:#333,stroke-width:2px
    classDef quantized stroke:#333,stroke-width:2px
    classDef recommended stroke:#333,stroke-width:2px
```

**Kvantointiselitys**:

- Alkuperäinen malli: M SK1bitkilat (erittäin suuri
- Q4: M SK1bitin integerit (75% pienemmät
- Q5/QM SK1 Useimpien käyttötapausten makea paikka
- Q8: lähelläM SK1 alkuperäinen laatu , yhä 4x pienempi

### Mallin valinta Hardware:n mukaan

| Malli | Suuruus SSK2QMSC3KM SK4M VSK6 VRAM-käytön käyttö \| Soveltuu 8~GB~?~ ||~ Soveltuvat 12~GB+?~ \ |~ Sovelletaan 16~GB&?~ ♪|~ Laadukkuus
|-------|---------------|------------|-----------|------------|------------|---------|
| **Phi-3Mini  (3.8BM SK2** | SSK1GB | \~4GB
| **Llama 2  7B** | 4.1GB
| **Mistral 7B** | 4.1GB
| **Gemma 7B** | 4.1GB
| **Llama 3  8B** |  4.7GB
| **Llama 2  13B** | 7.4GB | \~10GB

**GPU:n suositukset:**

- **8GB VRAM**: Aloitetaan **Mistral 7B** tai **Phi-3 Mini** (safestM SK1
- **12GB VRAM**: **Llama 3  8B** (paras laatu **Mistral 7B** (nopeampiM SK1
- **16GB VRAM**: **Llama 3  8B** tai yrittää **13B-mallit**
- **Vain CPU-**: Mitkä tahansa mallit toimivat, vain paljon hitaammin (käynnistetään Phin kanssaM SK3 Minin nopeuden osalta

**Suositukseni**: **[Mistral 7B](https://mistral.ai/)** ( viimeisin versioM SK1 tai **[Llama 3](https://ai.meta.com/llama/)** 8B

- Erinomainen laatu tekniselle kirjoittamiselle
- Soveltuu kaikkiin GPU-kokouksiin
- Hyvin nopeasti interaktiivisen käytön kannalta
- Hyvin noudattamaan ohjeita

## Laaditaan malleja

Muodot on jaettu Hugging Face-osoitteessa. MeM SK1 Käytämme kvantifioituja GGUF-versioita.

### GGUF-mallien löytäminen

1. Siihen [Hugging Face](https://huggingface.co/models)
2. haku: `"mistral 7b gguf"`
3. Ottakaa TheBloke's kvantisaatiot M SK1popularisinta)

**suorat yhteydet** (TheBloke

- [Mistral-7B -InstructM SK2v0.2-GGUF](https://huggingface.co/TheBloke/Mistral-7B-Instruct-v0.2-GGUF)
- [Llama-2-7B-ChatM SK2GGUF](https://huggingface.co/TheBloke/Llama-2-7B-Chat-GGUF)
- [Llama-3-8BM SK1Instruct-GGUF](https://huggingface.co/QuantFactory/Meta-Llama-3-8B-Instruct-GGUF)

### Laaditaan erityistä kvantisaatiota

```bash
# Install huggingface-cli
pip install huggingface-hub

# Download Mistral 7B Q5_K_M (recommended)
huggingface-cli download TheBloke/Mistral-7B-Instruct-v0.2-GGUF \
    mistral-7b-instruct-v0.2.Q5_K_M.gguf \
    --local-dir C:\models\mistral-7b \
    --local-dir-use-symlinks False
```

Vai laaditaan käsin:

1. Klikkää "Files and versions" -paneelia
2. Ottakaamme `mistral-7b-instruct-v0.2.Q5_K_M.gguf` (~4.8GB)
3. (Kliknikää ladata)
4. Save to `C:\models\mistral-7b\`

## LLamaSharp -järjestelmä

### NuGet-paketin asentaminen

```bash
cd Mostlylucid.BlogLLM.Core
dotnet add package LLamaSharp  # Latest version
dotnet add package LLamaSharp.Backend.Cuda12  # Latest, matching CUDA version
```

**Miksi kaksi pakettia?**

- `[LLamaSharp](https://github.com/SciSharp/LLamaSharp)` - Pääkirjasto
- `LLamaSharp.Backend.Cuda12` - [CUDA](https://developer.nvidia.com/cuda-toolkit) 12 GPU:n nopeuttamiseen tarkoitetut binaarit

### Vahvistetaan CUDA-puiteohjelma

LLamaSharp havaitsee automaattisesti CUDAn, jos se on otettu käyttöön oikein.

```csharp
using LLama;
using LLama.Common;

// Check if CUDA is available
bool cudaAvailable = NativeLibraryConfig.Instance.CudaEnabled;
Console.WriteLine($"CUDA Available: {cudaAvailable}");
```

Jos `false`, tarkistaa

1. CUDA 12.x asentattu (Parti 2)
2. `LLamaSharp.Backend.Cuda12` paketti on otettu käyttöön
3. PATH sisältää CUDA bin-tietokannan

## LLM-palvelun rakentaminen

### Mallin parametrit

```csharp
using LLama;
using LLama.Common;

namespace Mostlylucid.BlogLLM.Core.Services
{
    public class ModelParameters
    {
        public string ModelPath { get; set; } = string.Empty;
        public int ContextSize { get; set; } = 4096;  // Context window
        public int GpuLayerCount { get; set; } = 35;  // Layers on GPU (35 = all for 7B)
        public int Seed { get; set; } = 1337;  // For reproducibility
        public float Temperature { get; set; } = 0.7f;  // Creativity (0.0 = deterministic, 1.0 = creative)
        public float TopP { get; set; } = 0.9f;  // Nucleus sampling
        public int MaxTokens { get; set; } = 500;  // Max generation length
    }
}
```

**Parameterin selitykset**:

- **Kontext-koko**: Kuinka paljon tekstiä malli voi "katsoa
  
  - 4096 tokenit
  - Suurempi = enemmän kontekstia mutta hitaampaa ja enemmän VRAMia

- **GpuLayerCount**: Kuinka monta muuntajalaajaa käy GPU:ssa
  
  - 7B-mallit sisältävät  ~32-layereitä
  - 35
  - Alhaisemmat arvot = käyttävät vähemmän VRAMia mutta hitaammin

- **lämpötila**: Hallitsee sattumanvaraisuutta
  
  - 0.0 = valitsee aina todennäköisimmän token
  - 0.7 = hyvä tasapaino
  - 1.0+ = hyvin luova ( voi olla mieletöntä

- **TopP**: Ydinsampling
  
  - Consider tokens that make up 90% of probability mass
  - Estää hyvin epätodennäköisistä tokenseista peräisin olevan näytteenotton

### LLM-palvelun täytäntöönpano

```csharp
using LLama;
using LLama.Common;
using Microsoft.Extensions.Logging;

namespace Mostlylucid.BlogLLM.Core.Services
{
    public interface ILlmService
    {
        Task<string> GenerateAsync(string prompt, CancellationToken cancellationToken = default);
        Task<string> GenerateWithContextAsync(string prompt, List<string> contextChunks, CancellationToken cancellationToken = default);
    }

    public class LlmService : ILlmService, IDisposable
    {
        private readonly LLamaWeights _model;
        private readonly LLamaContext _context;
        private readonly ILogger<LlmService> _logger;
        private readonly ModelParameters _parameters;

        public LlmService(ModelParameters parameters, ILogger<LlmService> logger)
        {
            _parameters = parameters;
            _logger = logger;

            _logger.LogInformation("Loading model from {ModelPath}", parameters.ModelPath);

            // Configure model parameters
            var modelParams = new ModelParams(parameters.ModelPath)
            {
                ContextSize = (uint)parameters.ContextSize,
                GpuLayerCount = parameters.GpuLayerCount,
                Seed = (uint)parameters.Seed,
                UseMemoryLock = true,  // Keep model in RAM
                UseMemorymap = true    // Memory-map the model file
            };

            // Load model
            _model = LLamaWeights.LoadFromFile(modelParams);
            _context = _model.CreateContext(modelParams);

            _logger.LogInformation("Model loaded successfully. VRAM used: ~{VRAM}GB",
                EstimateVRAMUsage(parameters.GpuLayerCount));
        }

        public async Task<string> GenerateAsync(string prompt, CancellationToken cancellationToken = default)
        {
            var executor = new InteractiveExecutor(_context);

            var inferenceParams = new InferenceParams
            {
                Temperature = _parameters.Temperature,
                TopP = _parameters.TopP,
                MaxTokens = _parameters.MaxTokens,
                AntiPrompts = new[] { "\n\nUser:", "###" }  // Stop generation at these
            };

            var result = new StringBuilder();

            _logger.LogInformation("Generating response for prompt: {Prompt}", TruncateForLog(prompt));

            await foreach (var token in executor.InferAsync(prompt, inferenceParams, cancellationToken))
            {
                result.Append(token);
            }

            var response = result.ToString().Trim();
            _logger.LogInformation("Generated {Tokens} tokens", CountTokens(response));

            return response;
        }

        public async Task<string> GenerateWithContextAsync(
            string prompt,
            List<string> contextChunks,
            CancellationToken cancellationToken = default)
        {
            // Build prompt with retrieved context
            var fullPrompt = BuildContextualPrompt(prompt, contextChunks);

            _logger.LogInformation("Context chunks: {Count}, Total prompt tokens: ~{Tokens}",
                contextChunks.Count, CountTokens(fullPrompt));

            return await GenerateAsync(fullPrompt, cancellationToken);
        }

        private string BuildContextualPrompt(string userPrompt, List<string> contextChunks)
        {
            var sb = new StringBuilder();

            sb.AppendLine("You are a helpful writing assistant for a technical blog.");
            sb.AppendLine("Use the following excerpts from past blog posts as context:");
            sb.AppendLine();

            for (int i = 0; i < contextChunks.Count; i++)
            {
                sb.AppendLine($"--- Context {i + 1} ---");
                sb.AppendLine(contextChunks[i]);
                sb.AppendLine();
            }

            sb.AppendLine("---");
            sb.AppendLine();
            sb.AppendLine("Based on the context above, help with the following:");
            sb.AppendLine(userPrompt);
            sb.AppendLine();
            sb.AppendLine("Response:");

            return sb.ToString();
        }

        private int CountTokens(string text)
        {
            // Rough estimate: 1 token ≈ 4 characters
            return text.Length / 4;
        }

        private string TruncateForLog(string text, int maxLength = 100)
        {
            if (text.Length <= maxLength) return text;
            return text.Substring(0, maxLength) + "...";
        }

        private double EstimateVRAMUsage(int gpuLayers)
        {
            // Rough estimate for 7B model
            return (gpuLayers / 35.0) * 6.0;  // ~6GB for full 7B model
        }

        public void Dispose()
        {
            _context?.Dispose();
            _model?.Dispose();
        }
    }
}
```

**Miten se toimii**:

1. **Malli laaditaan**: Laaditaan GGUF-mallia VRAMiin määritettyjen parametrien avulla
2. **InteractiveExecutor -väline**: LLamaSharp
3. **InferAsynkki**: Yritykset tuottavat tokenit sellaisena kuin ne ovat
4. **Kontextirakentaminen**: Yhdistää käyttäjäpyynnön ja pyydetyt blogit
5. **--vastaiset toimenpiteet**: pysäyttää tuotannon tietyillä stringeilla (estää hajoamisen

### Palvelun testaaminen

```csharp
using Microsoft.Extensions.Logging;

class Program
{
    static async Task Main(string[] args)
    {
        // Setup logging
        var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
        var logger = loggerFactory.CreateLogger<LlmService>();

        // Configure model
        var parameters = new ModelParameters
        {
            ModelPath = @"C:\models\mistral-7b\mistral-7b-instruct-v0.2.Q5_K_M.gguf",
            ContextSize = 4096,
            GpuLayerCount = 35,
            Temperature = 0.7f,
            MaxTokens = 200
        };

        // Create service
        using var llmService = new LlmService(parameters, logger);

        // Test simple generation
        Console.WriteLine("=== Test 1: Simple Generation ===\n");
        var response1 = await llmService.GenerateAsync(
            "Explain what Docker Compose is in 2-3 sentences."
        );
        Console.WriteLine(response1);
        Console.WriteLine("\n");

        // Test with context
        Console.WriteLine("=== Test 2: Generation with Context ===\n");
        var context = new List<string>
        {
            "Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application's services.",
            "In development, Docker Compose makes it easy to spin up all dependencies (databases, caches, etc.) with one command: docker-compose up."
        };

        var response2 = await llmService.GenerateWithContextAsync(
            "Write an introduction paragraph for a blog post about using Docker Compose for development dependencies.",
            context
        );
        Console.WriteLine(response2);
    }
}
```

**Odotettu tulos**:

```
=== Test 1: Simple Generation ===

Docker Compose is a tool that allows you to define and run multi-container Docker applications using a simple YAML configuration file. It simplifies the process of managing multiple containers, networking, and volumes, making it ideal for development environments.

=== Test 2: Generation with Context ===

If you've ever found yourself juggling multiple terminal windows to start databases, caches, and other services for local development, Docker Compose is about to become your new best friend. This powerful tool lets you define your entire development environment in a single YAML file and spin everything up with one command. In this post, we'll explore how to leverage Docker Compose to manage all your development dependencies, making your local setup reproducible, shareable, and incredibly easy to manage.
```

Merkittävä! Malli toimii ja tuottaa johdonmukaistaM SK1 kontekstia - tietoinen teksti.

## Yhdenmukaistaminen ehdotuspaneelin kanssa

Nyt let's integroida LLM-generaation Windows-clientimme osasta 5.

### Ehdotuspalvelun päivitys

```csharp
namespace Mostlylucid.BlogLLM.Client.Services
{
    public class SuggestionService : ISuggestionService
    {
        private readonly BatchEmbeddingService _embeddingService;
        private readonly QdrantVectorStore _vectorStore;
        private readonly ILlmService _llmService;  // NEW

        public SuggestionService(
            BatchEmbeddingService embeddingService,
            QdrantVectorStore vectorStore,
            ILlmService llmService)  // NEW
        {
            _embeddingService = embeddingService;
            _vectorStore = vectorStore;
            _llmService = llmService;
        }

        public async Task<string> GenerateAiSuggestionAsync(
            string currentText,
            List<SimilarPost> context)
        {
            // Extract text from similar posts
            var contextChunks = context
                .Take(3)  // Top 3 most similar
                .Select(p => p.FullText)
                .ToList();

            // Determine what type of suggestion to generate
            var prompt = DeterminePromptType(currentText);

            // Generate suggestion
            var suggestion = await _llmService.GenerateWithContextAsync(
                prompt,
                contextChunks
            );

            return suggestion;
        }

        private string DeterminePromptType(string currentText)
        {
            // Analyze what user is writing
            var lines = currentText.Split('\n');
            var lastLine = lines.LastOrDefault(l => !string.IsNullOrWhiteSpace(l)) ?? "";

            // Is user starting a new section?
            if (lastLine.StartsWith("## "))
            {
                return "Suggest 3-5 bullet points for what this section could cover.";
            }

            // Is user writing code?
            if (lastLine.Contains("```"))
            {
                return "Suggest relevant code examples that might be useful here.";
            }

            // Is user writing an introduction?
            if (currentText.Length < 500 && currentText.Contains("## Introduction"))
            {
                return "Suggest 2-3 sentences to continue this introduction based on similar posts.";
            }

            // Default: continue current thought
            return "Suggest 1-2 sentences to continue the current paragraph in a natural way.";
        }
    }
}
```

### Tarkistetaan ehdotuksiaViewModel

```csharp
public partial class SuggestionsViewModel : ViewModelBase
{
    [RelayCommand]
    private async Task RegenerateSuggestion()
    {
        IsGenerating = true;
        AiSuggestion = "Generating...";

        try
        {
            var currentText = GetCurrentEditorText();  // From messaging
            var suggestion = await _suggestionService.GenerateAiSuggestionAsync(
                currentText,
                SimilarPosts.ToList()
            );

            AiSuggestion = suggestion;
        }
        catch (Exception ex)
        {
            AiSuggestion = $"Error: {ex.Message}";
        }
        finally
        {
            IsGenerating = false;
        }
    }
}
```

## suorituskyvyn optimointi

### Mallin talletus

Laaditaan mallia pyyntöjen välillä:

```csharp
public class LlmServiceFactory
{
    private static LlmService? _instance;
    private static readonly object _lock = new();

    public static LlmService GetInstance(ModelParameters parameters, ILogger<LlmService> logger)
    {
        if (_instance == null)
        {
            lock (_lock)
            {
                if (_instance == null)
                {
                    _instance = new LlmService(parameters, logger);
                }
            }
        }

        return _instance;
    }
}
```

### KV-tietokannan uudelleenkäyttö

LLamaSharp tukee KV-キャッシュin uudelleenkäyttöä nopeampien tulevien sukupolvien vuoksi:

```csharp
public class StatefulLlmService
{
    private readonly InferenceParams _defaultParams;
    private string _cachedPromptPrefix = string.Empty;

    public async Task<string> GenerateWithPrefixAsync(string prefix, string newPrompt)
    {
        // If prefix matches cached, reuse KV cache
        if (prefix == _cachedPromptPrefix)
        {
            // Only process new tokens
            return await GenerateAsync(newPrompt);
        }

        // Process entire prompt and cache
        _cachedPromptPrefix = prefix;
        return await GenerateAsync(prefix + newPrompt);
    }
}
```

Tämä on erityisen hyödyllistä käyttötarkoituksessamme - asiasisältöosuudet pysyvät ennallaan , vain käyttäjän kysymykset muuttuvat

### Määrärahat

Useiden ehdotusten osalta

```csharp
public async Task<List<string>> GenerateBatchAsync(List<string> prompts)
{
    var results = new List<string>();

    foreach (var prompt in prompts)
    {
        // With KV cache reuse, subsequent prompts are faster
        results.Add(await GenerateAsync(prompt));
    }

    return results;
}
```

## kirjallinen apu

Hyvät pyynnöt = hyvä tulos. Tässä on mallia erilaisille skenaarioilleM SK2

### Jatkaa kirjoittamista

```csharp
private string PromptContinueWriting(string currentText, List<string> context)
{
    return $@"You are a technical blog writing assistant.

Here are excerpts from similar blog posts:
{string.Join("\n\n", context.Select((c, i) => $"--- Post {i + 1} ---\n{c}"))}

Current draft:
{currentText}

Task: Suggest 2-3 sentences to naturally continue the current paragraph.
Keep the same technical depth and casual, pragmatic tone.

Suggestion:";
}
```

### Ehdota luokkarakennetta

```csharp
private string PromptSectionStructure(string sectionTitle, List<string> context)
{
    return $@"You are a technical blog writing assistant.

Similar sections from past posts:
{string.Join("\n\n", context)}

New section: {sectionTitle}

Task: Suggest 4-6 bullet points for what this section should cover.
Format as a markdown list.

Bullets:";
}
```

### Esimerkki

```csharp
private string PromptCodeExample(string description, List<string> context)
{
    return $@"You are a C# coding assistant.

Relevant code from past posts:
{string.Join("\n\n", context)}

Task: {description}

Provide a clean, well-commented C# code example.

Code:";
}
```

## Tietojen hallinta

Suurten mallien osalta muistinhallinta on ratkaisevaa,

### VRAM-käytön seuranta

```csharp
public class VramMonitor
{
    [DllImport("nvml.dll")]
    private static extern int nvmlDeviceGetMemoryInfo(IntPtr device, ref NvmlMemory memory);

    [StructLayout(LayoutKind.Sequential)]
    public struct NvmlMemory
    {
        public ulong Total;
        public ulong Free;
        public ulong Used;
    }

    public static (ulong used, ulong total) GetVramUsage()
    {
        // Simplified - actual implementation needs proper NVML initialization
        var memory = new NvmlMemory();
        // nvmlDeviceGetMemoryInfo(device, ref memory);

        return (memory.Used / 1024 / 1024, memory.Total / 1024 / 1024);  // Convert to MB
    }
}
```

### Unload Model When Inactive

```csharp
public class LlmServiceWithUnload : IDisposable
{
    private LlmService? _service;
    private readonly Timer _unloadTimer;
    private DateTime _lastUsed;

    public LlmServiceWithUnload()
    {
        _unloadTimer = new Timer(CheckForUnload, null, TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
    }

    private void CheckForUnload(object? state)
    {
        if (_service != null && (DateTime.Now - _lastUsed) > TimeSpan.FromMinutes(10))
        {
            _service.Dispose();
            _service = null;
            GC.Collect();
            Console.WriteLine("Model unloaded due to inactivity");
        }
    }

    public async Task<string> GenerateAsync(string prompt)
    {
        _lastUsed = DateTime.Now;

        if (_service == null)
        {
            // Reload model
            _service = CreateService();
        }

        return await _service.GenerateAsync(prompt);
    }
}
```

## Ongelmakäsittelyssä

LLM-järjestelmät voivat epäonnistua odottamattomilla tavoilla. Käsitellä hienosti:

```csharp
public async Task<string> GenerateWithRetryAsync(string prompt, int maxRetries = 3)
{
    for (int i = 0; i < maxRetries; i++)
    {
        try
        {
            return await GenerateAsync(prompt);
        }
        catch (OutOfMemoryException)
        {
            _logger.LogWarning("OOM error, reducing max tokens");
            _parameters.MaxTokens = Math.Max(100, _parameters.MaxTokens / 2);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Generation failed, attempt {Attempt}/{Max}", i + 1, maxRetries);

            if (i == maxRetries - 1) throw;

            await Task.Delay(1000 * (i + 1));  // Exponential backoff
        }
    }

    throw new Exception("Generation failed after retries");
}
```

## Lyhyesti sanottuna

Olemme integroineet onnistuneesti paikallisen LLM:n johtopäätöksen

1. ✅ valinta [LLamaSharp](https://github.com/SciSharp/LLamaSharp) C# integroimiseksi
2. ✅ Ymmärretty [GGUF-formatti](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md) ja kvantisointi
3. ✅ Valittu sopiva malli ([Mistral 7B](https://mistral.ai/) / [Llama 3](https://ai.meta.com/llama/) 8B)
4. ✅ Implemented LlmService with CUDA acceleration
5. ✅ Integroitu Windows-clientiin ehdotusten esittämiseksi
6. ✅ Rakennettu kiireellinen insinööri kirjoittamistehtäviin
7. ✅ Lisättiin suorituskyvyn optimointia (cachingM SK2 batching)
8. ✅ Handled memory management and errors

## Mikä's seuraavaM SK1

Siihen **[Osuus 7: sisältö generation & nopeutettu tekninen](/blog/building-a-lawyer-gpt-for-your-blog-part7)**, keskitymme kokonaisvaltaiseen sisältötuotantoon

- Kehitysaikaiset nopean tekniikan tekniikat
- Multi-turn vuoropuhelu iterative refinement
- Kontexti- ikkunanhallintastrategiat
- Laadun arviointi ja filtrointi
- Stylen johdonmukaisuuden noudattaminen
- Käsitellä koodiblokin luomista
- Real-maailman käyttömallit

Teemme järjestelmän todella hyödylliseksi päivittäisen blogin kirjoittamisen kannalta.

## Luettelo navigoinnista

- [Osa 1: Alkuperää &arkkitehtuuri](/blog/building-a-lawyer-gpt-for-your-blog-part1)
- [Osa 2: GPU-asetus & CUDA in C#](/blog/building-a-lawyer-gpt-for-your-blog-part2)
- [Osa 3: Ymmärrys sisällytyksistä & Vektortietokannat](/blog/building-a-lawyer-gpt-for-your-blog-part3)
- [Osa 4: Kulutusputken rakentaminen](/blog/building-a-lawyer-gpt-for-your-blog-part4)
- [Osa 5: Windows Client](/blog/building-a-lawyer-gpt-for-your-blog-part5)
- **Osa 6: Paikallinen LLM-integraatio** (this postM SK1
- [Osuus 7: sisältö generation & nopeutettu tekninen](/blog/building-a-lawyer-gpt-for-your-blog-part7)
- [Osuus 8: Kehitykselliset ominaisuudet & Tuottavuuden käyttöönotto](/blog/building-a-lawyer-gpt-for-your-blog-part8)

## Resurssit

- [LLamaSharp-asiakirja](https://scisharp.github.io/LLamaSharp/)
- [GGUF-formattimääräys](https://github.com/ggerganov/ggml/blob/master/docs/gguf.md)
- [TheBloke's mallikokonaisuus](https://huggingface.co/TheBloke)
- [llama.cpp GitHub](https://github.com/ggerganov/llama.cpp)

Kohdataan teidät [Osa 7](/blog/building-a-lawyer-gpt-for-your-blog-part7)!