開發工具:VS 2015
開發環境:.Net 4.0
使用技術:WPF
本篇文章內容:
本地部署DeepSeek以后一般使用網頁工具(如Chatbox)或者DOS窗口與其對話。本篇文章使用WPF創建一個基礎版的對話工具。
一、搭建本地DeepSeek環境
我參考的是一下幾個教程:
1、DeepSeek本地搭建部署+搭建知識庫+智能體詳細圖文教程
2、【問題記錄】DeepSeek本地部署遇到問題
3、公司數據不泄露,DeepSeek R1本地化部署+web端訪問+個人知識庫搭建與使用,喂飯級實操教程,老舊筆記本竟跑出企業級AI
4、【大語言模型】本地快速部署Ollama運行大語言模型詳細流程
二、vs2015 創建WPF項目
三、相關代碼如下
Windows窗口界面
<Window x:Class="DeepSeekAI2.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:DeepSeekAI2"mc:Ignorable="d"Title="MainWindow" Height="680" Width="800"><Grid Margin="10,0,15,5"><Grid.RowDefinitions><RowDefinition Height="8.5*"/><RowDefinition Height="1.5*"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="750"/></Grid.ColumnDefinitions><!--第一個格子,AI對話格子--><Grid Grid.Row="0" Grid.Column="0"><ListBox Name="ChatListBox" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding}" TextWrapping="Wrap" MaxWidth="730"/></DataTemplate></ListBox.ItemTemplate></ListBox></Grid><!--第二個格子,用戶輸入框--><Grid Grid.Row="1" Grid.Column="0"><Grid.ColumnDefinitions><ColumnDefinition Width="8*" /><ColumnDefinition Width="2*"/></Grid.ColumnDefinitions><!--輸入信息框--><Grid Grid.Column="0"><TextBox Name="InputTextBox" HorizontalAlignment="Left" VerticalAlignment="Bottom" KeyDown="InputTextBox_KeyDown"Height="62" Width="522" Margin="61,0,0,14" /></Grid><!--發送信息按鈕框--><Grid Grid.Column="1"><Button Name="SendButton" Content="Send" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,58,20" Width="90" Height="50" Click="SendButton_Click" FontFamily="Arial Black" FontSize="13" Foreground="#FF424234"/></Grid><Grid Grid.Column="1"><Button Name="SendButton1" Content="new" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,2,60" Width="30" Height="30" Click="SendButton_Click1" FontFamily="Cambria" Foreground="#FF424234" Background="#FFB6F5C2"/></Grid></Grid></Grid>
</Window>
后端代碼
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
using System.Net;namespace DeepSeekAI2
{/// <summary>/// MainWindow.xaml 的交互邏輯/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}/// <summary>/// 輸入按鈕框/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void InputTextBox_KeyDown(object sender, KeyEventArgs e){if (e.Key == Key.Enter){RunAI();//InputTextBox.Text = "";}}/// <summary>/// 確認發送按鈕/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void SendButton_Click(object sender, RoutedEventArgs e){// 異步方法需在同步上下文中調用(需手動處理)RunAI();//InputTextBox.Text = "";}// 用于存儲對話的歷史記錄static StringBuilder conversationHistory = new StringBuilder();static string apiUrl = "http://localhost:11434/api/generate";public void RunAI(){// 用戶輸入string userInput = InputTextBox.Text;// 如果輸入不正確,不輸出if (userInput.ToLower() == "" || userInput.ToLower() == "\n"){return;}// 用戶輸入添加到歷史對話記錄conversationHistory.AppendLine($"用戶: {userInput}");ChatListBox.Items.Add("-----------用戶:-----------");ChatListBox.Items.Add(userInput);var requestData = new{model = "deepseek-r1:1.5b",prompt = conversationHistory.ToString(),stream = true};string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(requestData);byte[] byteArray = Encoding.UTF8.GetBytes(jsonContent);HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);request.Method = "POST";request.ContentType = "application/json";request.ContentLength = byteArray.Length;using (Stream dataStream = request.GetRequestStream()){dataStream.Write(byteArray, 0, byteArray.Length);}try{using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())using (Stream responseStream = response.GetResponseStream())using (StreamReader reader = new StreamReader(responseStream)){string line;string line2 = "";while ((line = reader.ReadLine()) != null){if (!string.IsNullOrEmpty(line)){dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(line);if (result != null && result.response != null){//Console.Write(result.response);//Console.Out.Flush(); // 強制刷新控制臺輸出//ChatListBox.Items.Add(result.response);line2 += result.response;}}}// 處理AI回話// 去掉所有的換行符line2 = line2.Replace("\n\n", "");// 使用正則表達式去掉 <think> 和 </think> 標簽line2 = Regex.Replace(line2, @"<\/?think>", "\n");// 去掉開頭的換行符line2 = line2.TrimStart('\r', '\n');ChatListBox.Items.Add("-----------DeepSeek: -----------");//Console.WriteLine(); AI回話DeePSeek回話 line2ChatListBox.Items.Add(line2);conversationHistory.AppendLine($"DeepSeek: {line2}");line2 = "";}InputTextBox.Text = "";}catch (WebException ex){MessageBox.Show("請求異常: " + ex.Message);InputTextBox.Text = "";}}/// <summary>/// 開啟新的對話/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void SendButton_Click1(object sender, RoutedEventArgs e){//1 清空歷史記錄conversationHistory.Clear();//2 清空 ListBox 的內容ChatListBox.Items.Clear();//3 清空輸入框InputTextBox.Text = "";}}
}
四、內容介紹
static string apiUrl = "http://localhost:11434/api/generate";
其中這個代碼是本地DeepSeek默認的調用接口,如果自己修改了相關內容將此修改就可以
model = "deepseek-r1:1.5b"
這串代碼的意思是指定使用本地安裝的某個DeepSeek版本。
因為7b的版本在我電腦上太慢。所以直接使用最快的模型。
五、完成效果如下
這樣就搭建了基礎的對話模型。大家可以不斷優化,做一個自己的對話模型。