欢迎大家来到IT世界,在知识的湖畔探索吧!
用代码,缓解焦虑,舒张血压,难得的宁静。
继续,借用Microsoft.Extensions.AI,用C#,与本地Ollama模型对话。
一、引用包
包括2个:

欢迎大家来到IT世界,在知识的湖畔探索吧!
二、添加控件
添加webview2
三、输入代码
using System; using System.Drawing; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Extensions.AI; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; namespace 财务指标分析最终版 { public partial class MicrosoftExtensionsAI对话 : Form { public string strAsk = ""; // 用于存储用户输入的问题 public string modelName = "qwen2.5:3b"; public MicrosoftExtensionsAI对话() { InitializeComponent(); InitializeWebView2(); } private async void MicrosoftExtensionsAI对话_Load(object sender, EventArgs e) { // 延迟 1 秒后执行 模型对话() await Task.Delay(500); // 延迟 1 秒(1000 毫秒) this.Text = strAsk; 模型对话(); } private async void InitializeWebView2() { try { // 初始化 WebView2 环境 await webView21.EnsureCoreWebView2Async(null); // 设置初始 HTML 内容 webView21.CoreWebView2.NavigateToString("
"); // 设置 WebView2 的背景颜色为系统控件颜色 await SetWebView2BackgroundColor(SystemColors.Control); } catch (Exception ex) { MessageBox.Show($"WebView2 初始化失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private async Task SetWebView2BackgroundColor(Color color) { try { // 将 SystemColors.Control 转换为 RGB 格式 string rgbColor = $"rgb({color.R}, {color.G}, {color.B})"; // 设置 WebView2 的背景颜色 string script = $@" document.body.style.backgroundColor = '{rgbColor}'; "; await webView21.CoreWebView2.ExecuteScriptAsync(script); } catch (Exception ex) { MessageBox.Show($"设置 WebView2 背景颜色失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private async void 模型对话() { // 清空之前的输出 await webView21.CoreWebView2.ExecuteScriptAsync("document.getElementById('content').innerHTML = '';"); try { Uri uri = new Uri("http://localhost:11434"); IChatClient chatClient = new OllamaChatClient(uri, modelName); var responseStream = chatClient.GetStreamingResponseAsync(strAsk); // 用于缓存响应内容 var responseBuilder = new StringBuilder(); var lastUpdateTime = DateTime.Now; // 逐段读取响应并更新 WebView2 await foreach (var message in responseStream) { // 将消息追加到缓存中 responseBuilder.Append(message.ToString()); // 定期更新 WebView2(例如每 100ms 或每 10 条消息) if ((DateTime.Now - lastUpdateTime).TotalMilliseconds > 100 || responseBuilder.Length > 1000) { // 将内容追加到 WebView2 await AppendToWebView2(responseBuilder.ToString()); // 清空缓存 responseBuilder.Clear(); lastUpdateTime = DateTime.Now; } } // 追加剩余内容 if (responseBuilder.Length > 0) { await AppendToWebView2(responseBuilder.ToString()); } } catch (Exception ex) { // 异常处理 MessageBox.Show($"发生错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private async Task AppendToWebView2(string content) { try { // 将内容追加到 WebView2 的 HTML 中 string appendScript = $@" var contentDiv = document.getElementById('content'); contentDiv.innerHTML += '{EscapeJavaScriptString(content)}'; "; await webView21.CoreWebView2.ExecuteScriptAsync(appendScript); // 增加短暂延迟,确保内容渲染完成 await Task.Delay(10); // 滚动到底部 string scrollScript = @" var contentDiv = document.getElementById('content'); contentDiv.scrollTop = contentDiv.scrollHeight; "; await webView21.CoreWebView2.ExecuteScriptAsync(scrollScript); } catch (Exception ex) { MessageBox.Show($"更新 WebView2 失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string EscapeJavaScriptString(string input) { // 转义 JavaScript 字符串中的特殊字符 return input.Replace("\\", "\\\\") .Replace("'", "\\'") .Replace("\"", "\\\"") .Replace("\r", "\\r") .Replace("\n", "\\n"); } } }
欢迎大家来到IT世界,在知识的湖畔探索吧!
四、对话结果
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/116422.html