[C#] Hướng dẫn viết ứng dụng chat với Gemini AI Google Winform
Gemini AI là gì?
Gemini AI dòng mô hình ngôn ngữ lớn mới nhất của Google, cung cấp tất cả thông tin cần thiết để bắt đầu tạo ứng dụng bằng Gemini.Đầu tiên, các bạn cần tạo một tài khoản API key.
Tiếp đến, các bạn tạo một API key để sử dụng như hình bên dưới:
Tiếp đến, các bạn tạo project C#, vào cài đặt thư viện Google_GenerativeAI từ nuget:
Thiết kế giao diện chat Winform như hình bên dưới:
Chúc các bạn thành công với thủ thuật trên, để tạo cho mình một ứng dụng chat AT tốt nhất nhé
Tiếp đến, các bạn tạo project C#, vào cài đặt thư viện Google_GenerativeAI từ nuget:
PM> Install-Package Google_GenerativeAI
Thiết kế giao diện chat Winform như hình bên dưới:
Full source code C#:
using GenerativeAI.Methods; using GenerativeAI.Models; using GenerativeAI.Types; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GeminiAIDemo { public partial class Form1 : Form { ChatSession chatSession; public string apiKey = "AIzaSyCjhe255nXjOQwst6NM6RrXCbz03xl66HM"; public Form1() { InitializeComponent(); } private async void btnSend_Click(object sender, EventArgs e) { var message = txtMessage.Text.Trim(); await SendMessageAsync(message); } private async Task SendMessageAsync(string message) { if (btnSend.Text != "Send message") return; if (message.Length > 0) { txtMessage.Text = ""; btnSend.Text = "Waiting..."; txtBody.SelectionAlignment = HorizontalAlignment.Left; txtBody.SelectionColor = Color.Blue; txtBody.AppendText($"Me: {message}\n"); txtBody.SelectionAlignment = HorizontalAlignment.Right; txtBody.SelectionColor = Color.Red; var result = await chatSession.SendMessageAsync(message); txtBody.AppendText($"Gemini AI: {result}\n"); txtBody.SelectionAlignment = HorizontalAlignment.Left; txtBody.SelectionColor = txtBody.ForeColor; btnSend.Text = "Send message"; txtBody.ScrollToCaret(); } } private void Form1_Load(object sender, EventArgs e) { var model = new GenerativeModel(apiKey); chatSession = model.StartChat(new StartChatParams()); } private async void txtMessage_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { var message = txtMessage.Text.Trim(); await SendMessageAsync(message); } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("https://hung.pro.vn/"); } } }
Chúc các bạn thành công với thủ thuật trên, để tạo cho mình một ứng dụng chat AT tốt nhất nhé
Theo LapTrinhVB.Net
2 comments:
chất lượng đó e
e cảm ơn a, cập nhật thêm nhiều thủ thuật hữu ích cho it nữa a nhé <3
Post a Comment