คุณเขียนโค้ด C# ได้ไหม
- User
คุณเขียนโค้ด C# ได้ไหม
Assistant
ได้ครับ ผมสามารถเขียนโค้ด C# ได้ ไม่ว่าจะเป็น:
- Console Applications
- Web Applications (ASP.NET Core, Blazor)
- Desktop Applications (WPF, WinForms)
- APIs และ Web Services
- Class Libraries
- Game Development (Unity)
- และอื่นๆ
คุณต้องการให้ช่วยเขียนโค้ด C# แบบไหนครับ? หรือมีโปรเจคที่อยากให้ช่วยไหม?
- User
ช่วยบอกวิธี เขียนโค้ด C# Windowsform เพื่อให้ user upload ไฟล์ excel แล้วทำ RAG ด้วย LangChain อยู่เบื้องหลัง โดยอาจใช้ llama 3.2 ทำงานแบบ local
Assistant
ผมจะแนะนำวิธีสร้าง Windows Forms Application ที่ทำ RAG กับไฟล์ Excel โดยใช้ LangChain และ Llama 3.2 แบบ local ครับ
1. ติดตั้ง NuGet Packages ที่จำเป็น
<PackageReference Include="LangChain" Version="0.13.0" /> <PackageReference Include="EPPlus" Version="7.0.0" /> <PackageReference Include="Microsoft.SemanticKernel" Version="1.3.0" /> <PackageReference Include="LlamaSharp" Version="0.9.1" /> <PackageReference Include="System.Memory" Version="4.5.5" />2. สร้าง Windows Form UI
public partial class MainForm : Form { private TextBox txtFilePath; private Button btnBrowse; private Button btnUpload; private TextBox txtQuestion; private Button btnAsk; private RichTextBox rtbAnswer; private ProgressBar progressBar; public MainForm() { InitializeComponent(); SetupUI(); } private void SetupUI() { // File upload controls var lblFile = new Label { Text = "Excel File:", Location = new Point(10, 20), Size = new Size(80, 23) }; txtFilePath = new TextBox { Location = new Point(100, 20), Size = new Size(300, 23), ReadOnly = true }; btnBrowse = new Button { Text = "Browse", Location = new Point(410, 18), Size = new Size(75, 25) }; btnUpload = new Button { Text = "Upload & Process", Location = new Point(490, 18), Size = new Size(120, 25) }; // Question controls var lblQuestion = new Label { Text = "Question:", Location = new Point(10, 60), Size = new Size(80, 23) }; txtQuestion = new TextBox { Location = new Point(100, 60), Size = new Size(400, 23) }; btnAsk = new Button { Text = "Ask", Location = new Point(510, 58), Size = new Size(100, 25) }; // Answer display var lblAnswer = new Label { Text = "Answer:", Location = new Point(10, 100), Size = new Size(80, 23) }; rtbAnswer = new RichTextBox { Location = new Point(10, 130), Size = new Size(600, 300) }; // Progress bar progressBar = new ProgressBar { Location = new Point(10, 440), Size = new Size(600, 23), Visible = false }; // Add controls to form Controls.AddRange(new Control[] { lblFile, txtFilePath, btnBrowse, btnUpload, lblQuestion, txtQuestion, btnAsk, lblAnswer, rtbAnswer, progressBar }); // Event handlers btnBrowse.Click += BtnBrowse_Click; btnUpload.Click += BtnUpload_Click; btnAsk.Click += BtnAsk_Click; } }3. Excel Reader Class
using OfficeOpenXml; using System.Data; public class ExcelReader { public static List<string> ReadExcelToChunks(string filePath, int chunkSize = 500) { var chunks = new List<string>(); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; using (var package = new ExcelPackage(new FileInfo(filePath))) { foreach (var worksheet in package.Workbook.Worksheets) { var rowCount = worksheet.Dimension?.Rows ?? 0; var colCount = worksheet.Dimension?.Columns ?? 0; var currentChunk = new StringBuilder(); currentChunk.AppendLine($"Worksheet: {worksheet.Name}"); for (int row = 1; row <= rowCount; row++) { var rowData = new List<string>(); for (int col = 1; col <= colCount; col++) { var cellValue = worksheet.Cells[row, col].Value?.ToString() ?? ""; rowData.Add(cellValue); } currentChunk.AppendLine(string.Join(" | ", rowData)); // Create chunk when size limit reached if (currentChunk.Length > chunkSize && row < rowCount) { chunks.Add(currentChunk.ToString()); currentChunk.Clear(); currentChunk.AppendLine($"Worksheet: {worksheet.Name} (continued)"); } } if (currentChunk.Length > 0) { chunks.Add(currentChunk.ToString()); } } } return chunks; } }4. RAG Implementation with Local Llama
using LangChain.Chains; using LangChain.Memory; using LangChain.Providers.LlamaSharp; using LlamaSharp; public class LocalRAGService { private string modelPath; private List<string> documentChunks; private LlamaSharpModelInstruction llm; private InMemoryVectorStore vectorStore; public LocalRAGService(string modelPath) { this.modelPath = modelPath; this.documentChunks = new List<string>(); InitializeLlama(); } private void InitializeLlama() { // Initialize Llama model var parameters = new ModelParams(modelPath) { ContextSize = 2048, GpuLayerCount = 20, // Adjust based on your GPU Threads = 8 }; llm = new LlamaSharpModelInstruction(new LlamaWeights(modelPath), parameters); // Initialize vector store for embeddings vectorStore = new InMemoryVectorStore(); } public async Task ProcessExcelDocuments(List<string> chunks, IProgress<int> progress = null) { documentChunks = chunks; // Generate embeddings for each chunk for (int i = 0; i < chunks.Count; i++) { var embedding = await GenerateEmbedding(chunks[i]); await vectorStore.AddDocumentAsync(new Document { PageContent = chunks[i], Metadata = new Dictionary<string, object> { ["index"] = i } }, embedding); progress?.Report((i + 1) * 100 / chunks.Count); } } public async Task<string> AskQuestion(string question) { // Search for relevant chunks var relevantDocs = await SearchRelevantDocuments(question, topK: 3); // Create context from relevant documents var context = string.Join("\n\n", relevantDocs.Select(d => d.PageContent)); // Create prompt var prompt = $@"Based on the following Excel data, please answer the question. Context: {context} Question: {question} Answer:"; // Generate response var response = await llm.GenerateAsync(prompt, new InferenceParams { MaxTokens = 512, Temperature = 0.7f, TopP = 0.9f }); return response; } private async Task<List<float>> GenerateEmbedding(string text) { // Simple embedding generation - in production, use proper embedding model // This is a placeholder - you should use a real embedding model var hash = text.GetHashCode(); var embedding = new List<float>(); var rand = new Random(hash); for (int i = 0; i < 384; i++) // 384-dimensional embedding { embedding.Add((float)rand.NextDouble()); } return embedding; } private async Task<List<Document>> SearchRelevantDocuments(string query, int topK = 3) { var queryEmbedding = await GenerateEmbedding(query); return await vectorStore.SimilaritySearchAsync(queryEmbedding, topK); } }5. Form Event Handlers
public partial class MainForm : Form { private LocalRAGService ragService; private string currentFilePath; private void BtnBrowse_Click(object sender, EventArgs e) { using (var openFileDialog = new OpenFileDialog()) { openFileDialog.Filter = "Excel Files|*.xlsx;*.xls"; openFileDialog.Title = "Select Excel File"; if (openFileDialog.ShowDialog() == DialogResult.OK) { txtFilePath.Text = openFileDialog.FileName; currentFilePath = openFileDialog.FileName; } } } private async void BtnUpload_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(currentFilePath)) { MessageBox.Show("Please select an Excel file first."); return; } try { progressBar.Visible = true; btnUpload.Enabled = false; // Read Excel file var chunks = ExcelReader.ReadExcelToChunks(currentFilePath); // Initialize RAG service with Llama model if (ragService == null) { // Update this path to your Llama 3.2 model location var modelPath = @"C:\models\llama-3.2-3b-instruct.gguf"; ragService = new LocalRAGService(modelPath); } // Process documents var progress = new Progress<int>(percent => progressBar.Value = percent); await Task.Run(() => ragService.ProcessExcelDocuments(chunks, progress)); MessageBox.Show("Excel file processed successfully!"); btnAsk.Enabled = true; } catch (Exception ex) { MessageBox.Show($"Error processing file: {ex.Message}"); } finally { progressBar.Visible = false; btnUpload.Enabled = true; } } private async void BtnAsk_Click(object sender, EventArgs e) { if (ragService == null) { MessageBox.Show("Please upload and process an Excel file first."); return; } if (string.IsNullOrWhiteSpace(txtQuestion.Text)) { MessageBox.Show("Please enter a question."); return; } try { btnAsk.Enabled = false; rtbAnswer.Text = "Thinking..."; var answer = await Task.Run(() => ragService.AskQuestion(txtQuestion.Text)); rtbAnswer.Text = answer; } catch (Exception ex) { rtbAnswer.Text = $"Error: {ex.Message}"; } finally { btnAsk.Enabled = true; } } }6. การติดตั้ง Llama 3.2 Model
- ดาวน์โหลด Llama 3.2 GGUF model จาก Hugging Face
- วางไฟล์ model ในโฟลเดอร์ที่เหมาะสม (เช่น
C:\models\) - อัพเดท path ใน code
หมายเหตุสำคัญ:
- Model Path: ต้องอัพเดท path ของ Llama model ให้ถูกต้อง
- GPU Support: ถ้ามี GPU ให้ปรับ
GpuLayerCountตามความเหมาะสม - Embeddings: ตัวอย่างนี้ใช้ embedding แบบง่าย ในการใช้งานจริงควรใช้ embedding model ที่ดีกว่า
- Memory Usage: Llama 3.2 ต้องการ RAM ค่อนข้างมาก (8-16GB ขึ้นไป)
ต้องการให้อธิบายส่วนไหนเพิ่มเติมไหมครับ?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.