AIGC标识 Ollama 本地聊天桌面程序 —— 开发说明文档

Ollama 本地聊天桌面程序 —— 开发说明文档

目标:用 VB.NET + WinForms 做一个连接本地 Ollama 服务的图形化聊天窗口,支持模型选择、流式打字机输出、Markdown 渲染、护眼暗色主题、窗口自适应最大化。本文档讲解如何从零编写该程序,并附完整源代码与避坑注意事项。


一、项目概述

项目 说明
运行平台 Windows 桌面程序(WinForms)
开发语言 VB.NET
后端服务 本机 Ollama,默认地址 http://127.0.0.1:11434
对话接口 POST /api/chat(流式返回 NDJSON,每行一个 JSON)
模型列表接口 GET /api/tags
富文本渲染 WebView2 + Markdig(把模型输出的 Markdown 渲染成网页)
主题 护眼暗绿配色(背景 #1A2421、面板 #24302C、正文 #FAF7F0)

界面布局:顶部「模型选择 + 状态标签」、中部「WebView2 聊天显示区(Fill 填充)」、底部「输入框 + 发送/停止/清空按钮」。


二、环境准备

2.1 安装 Ollama 并拉取模型

  1. 到 ollama.com 下载并安装 Ollama,安装后它会在 127.0.0.1:11434 常驻服务。
  2. 命令行拉取模型,例如:
    ollama pull qwen3:0.6b
    
  3. 验证服务是否就绪:浏览器打开 http://127.0.0.1:11434,返回 Ollama is running 即可。

2.2 创建 Visual Basic WinForms 项目

  • Visual Studio → 新建项目 → 选 「Windows 窗体应用 (.NET Framework)」(推荐 .NET Framework 4.7.2+,WebView2 兼容最稳)。
  • 项目里删除默认的 Form1,新建一个 Public Class ChatForm,即本文的源代码。

2.3 安装 NuGet 依赖(两个)

在「工具 → NuGet 包管理器 → 管理解决方案的 NuGet 包」中安装:

包名 作用
Markdig 把 Markdown 文本转成 HTML
Microsoft.Web.WebView2 内嵌 Edge 内核浏览器,渲染 Markdown 结果

注意:WebView2 不仅需要 NuGet 包,运行机器上还要装有 WebView2 Runtime(Win11 自带;老 Win10/Win7 需让用户安装 Evergreen Runtime)。


三、整体架构

ChatForm
  BuildUI()          构建界面(顶部/中部/底部三区 + 控件声明 + 事件绑定)
  OnResize()         重写:最大化/拉伸时动态设输入框宽度,左右边距永远对称
  Form_Load()        初始化 WebView2,注入护眼 CSS 骨架,加载模型列表
  LoadModelsAsync()  GET /api/tags -> 填充下拉框 -> 默认选 qwen
  SendMessageAsync() 流式 POST /api/chat -> 边读边渲染 -> 存历史
  RenderMarkdown()   Markdig 转 HTML -> 用 JS 增量更新 #content 并自动滚到底
  BtnStop_Click()    Cancel TokenSource,中断流式读取
  BtnClear_Click()   清空 fullMd 与 history

四、核心模块讲解

4.1 复用一个 HttpClient + 取消令牌

程序级 http As HttpClient 只 new 一次(New() 里),超时设为无限(流式回答可能很久)。每次发送新建一个 CancellationTokenSource,点「停止」时 cts.Cancel() 立刻断开流。关闭窗体时 http.Dispose()。

4.2 流式读取(打字机效果的关键)

用 HttpCompletionOption.ResponseHeadersRead 拿到响应后不等整体下载完,而是把响应体当逐行流读取。Ollama 每吐一段就一行 JSON:

Do While Not reader.EndOfStream
    Dim line = Await reader.ReadLineAsync(...)   ' 每行是一个完整 JSON
    Using doc = JsonDocument.Parse(line)
        ' 用 TryGetProperty 判断字段是否存在,再取 message.content
    End Using
Loop

必须用 TryGetProperty(而不是 GetProperty),因为最后一行 {"done":true} 里没有 message 字段,直接 GetProperty 会抛 KeyNotFoundException。

4.3 渲染节流 + JS 增量更新(解决跳动)

高频 token 不能每来一个字就整页刷新,否则界面狂闪。做法:

  • 节流:If DateTime.Now - lastRender > TimeSpan.FromMilliseconds(120) 才刷新,约 8 帧/秒,肉眼顺滑又不卡。
  • JS 增量写:只更新 <div id='content'> 的 innerHTML,再用 requestAnimationFrame 把页面滚到底部。只刷新内容区,不重新 Navigate 整个页面,彻底消除闪烁/跳动。

4.4 自适应最大化(OnResize 动态设宽)

输入框宽度不用硬编码,也不用 Anchor Top|Bottom(会被压扁)。改用重写 OnResize:

Protected Overrides Sub OnResize(e As EventArgs)
    MyBase.OnResize(e)
    Dim w As Integer = bottomPanel.ClientSize.Width - 24   ' 左右各留 12
    If w > 0 Then txtInput.Width = w
End Sub

输入框 Anchor 只留 Top | Left,左右边距永远各 12 像素,最大化也对称。

4.5 护眼配色

窗体、面板用 ColorTranslator.FromHtml("#1A2421" / "#24302C");WebView2 的暗色由 Form_Load 注入的 CSS <style> 控制(含 ::-webkit-scrollbar 自定义滚动条配色),保证网页与窗体色调统一。


五、完整源代码(ChatForm.vb)

Imports System.Net.Http
Imports System.Text
Imports System.Text.Json
Imports System.Threading
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports System.Drawing
Imports System.IO
Imports Markdig
Imports Microsoft.Web.WebView2.WinForms

Public Class ChatForm
    Inherits System.Windows.Forms.Form

    ' ===== 配置 =====
    Private Const BaseUrl As String = "http://127.0.0.1:11434"

    ' ===== 控件 =====
    Private bottomPanel As Panel
    Private txtOutput As Microsoft.Web.WebView2.WinForms.WebView2
    Private txtInput As System.Windows.Forms.RichTextBox
    Private cmbModels As System.Windows.Forms.ComboBox
    Private btnSend As System.Windows.Forms.Button
    Private btnStop As System.Windows.Forms.Button
    Private btnClear As System.Windows.Forms.Button
    Private lblStatus As System.Windows.Forms.Label
    Private lblModel As System.Windows.Forms.Label

    ' ===== 状态 =====
    Private ReadOnly http As HttpClient
    Private cts As CancellationTokenSource = Nothing
    Private ReadOnly history As New List(Of Dictionary(Of String, String))
    Private fullMd As String = ""
    Private lastRender As DateTime = DateTime.MinValue
    Private isSending As Boolean = False
    Private isWebViewReady As Boolean = False

    Public Sub New()
        BuildUI()
        http = New HttpClient()
        http.Timeout = System.Threading.Timeout.InfiniteTimeSpan
        AddHandler Me.Load, AddressOf Form_Load
    End Sub

    ' ===== 窗体加载 =====
    Private Async Sub Form_Load(sender As Object, e As EventArgs)
        ' 初始化 WebView2
        Await txtOutput.EnsureCoreWebView2Async()
        AddHandler txtOutput.CoreWebView2.NavigationCompleted, AddressOf WebView_NavigationCompleted

        ' 只加载一次基础 HTML 骨架(已应用柔和护眼暗色主题)
        Dim baseHtml = "<!DOCTYPE html><html><head><meta charset='utf-8'>" &
            "<style>" &
            "html{scroll-behavior:auto;}" &
            "body{font-family:'Microsoft YaHei UI',sans-serif;font-size:15px;line-height:1.7;padding:12px;margin:0;word-wrap:break-word;background-color:#1A2421;color:#FAF7F0;}" &
            "pre{background:#24302C;padding:10px;border-radius:5px;overflow-x:auto;color:#FAF7F0;}" &
            "code{background:#24302C;padding:2px 4px;border-radius:3px;font-family:Consolas,monospace;color:#F4D06F;}" &
            "pre code{background:none;padding:0;color:#FAF7F0;}" &
            "blockquote{border-left:4px solid #9FB3A8;margin-left:0;padding-left:12px;color:#9FB3A8;}" &
            "table{border-collapse:collapse;width:100%;color:#FAF7F0;}" &
            "td,th{border:1px solid #9FB3A8;padding:6px 10px;}" &
            "a{color:#F4D06F;text-decoration:none;}" &
            "a:hover{text-decoration:underline;}" &
            "img{max-width:100%;}" &
            "::-webkit-scrollbar{width:8px;height:8px;}" &
            "::-webkit-scrollbar-track{background:#1A2421;}" &
            "::-webkit-scrollbar-thumb{background:#9FB3A8;border-radius:4px;}" &
            "::-webkit-scrollbar-thumb:hover{background:#79716B;}" &
            "</style></head><body><div id='content'></div></body></html>"

        txtOutput.NavigateToString(baseHtml)
        RenderMarkdown("")
        LoadModelsAsync()
    End Sub

    ' ===== 导航完成事件 =====
    Private Sub WebView_NavigationCompleted(sender As Object, e As Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs)
        If e.IsSuccess Then
            isWebViewReady = True
        End If
    End Sub

    ' ===== 界面构建(自适应最大化 + 护眼配色 + 悬停高亮 修正版) =====
    Private Sub BuildUI()
        Me.Text = "Ollama 本地聊天"
        Me.Size = New System.Drawing.Size(900, 700)
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.MinimumSize = New System.Drawing.Size(600, 400)
        Me.BackColor = System.Drawing.ColorTranslator.FromHtml("#1A2421")

        ' 1. 顶部面板(固定在顶部,宽度随窗体拉伸)
        Dim topPanel As New Panel With {
            .Dock = DockStyle.Top,
            .Height = 40,
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#1A2421")
        }

        lblModel = New System.Windows.Forms.Label With {
            .Text = "模型:",
            .Location = New System.Drawing.Point(12, 12),
            .AutoSize = True,
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0")
        }
        cmbModels = New System.Windows.Forms.ComboBox With {
            .Location = New System.Drawing.Point(60, 8),
            .Width = 300,
            .DropDownStyle = ComboBoxStyle.DropDownList,
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#24302C"),
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0"),
            .FlatStyle = FlatStyle.Flat
        }
        lblStatus = New System.Windows.Forms.Label With {
            .Text = "连接中...",
            .Location = New System.Drawing.Point(380, 12),
            .AutoSize = True,
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#9FB3A8")
        }

        topPanel.Controls.Add(lblModel)
        topPanel.Controls.Add(cmbModels)
        topPanel.Controls.Add(lblStatus)

        ' 2. 底部面板(固定在底部,宽度随窗体拉伸)
        bottomPanel = New Panel With {
            .Dock = DockStyle.Bottom,
            .Height = 150,
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#1A2421")
        }

        ' 输入框:直接加入 bottomPanel(不再套 inputPanel,避免控件被重复 Add 抛异常)
        ' Anchor 只保留 Top|Left,宽度和左右边距由 OnResize 动态计算,永远对称
        txtInput = New System.Windows.Forms.RichTextBox With {
            .Location = New System.Drawing.Point(12, 10),
            .Size = New System.Drawing.Size(860, 80),
            .ScrollBars = RichTextBoxScrollBars.ForcedVertical,
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#24302C"),
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0"),
            .BorderStyle = BorderStyle.Fixed3D,
            .Font = New System.Drawing.Font("Microsoft YaHei UI", 10.5F),
            .WordWrap = True,
            .Anchor = AnchorStyles.Top Or AnchorStyles.Left
        }

        bottomPanel.Controls.Add(txtInput)

        btnSend = New System.Windows.Forms.Button With {
            .Text = "发送 (Ctrl+Enter)",
            .Location = New System.Drawing.Point(12, 100),
            .Size = New System.Drawing.Size(150, 35),
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#24302C"),
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0"),
            .FlatStyle = FlatStyle.Flat,
            .Cursor = Cursors.Hand,
            .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
        }
        btnSend.FlatAppearance.MouseOverBackColor = System.Drawing.ColorTranslator.FromHtml("#2E3D38")
        btnSend.FlatAppearance.MouseDownBackColor = System.Drawing.ColorTranslator.FromHtml("#1E2925")

        btnStop = New System.Windows.Forms.Button With {
            .Text = "停止",
            .Location = New System.Drawing.Point(170, 100),
            .Size = New System.Drawing.Size(80, 35),
            .Enabled = False,
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#24302C"),
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0"),
            .FlatStyle = FlatStyle.Flat,
            .Cursor = Cursors.Hand,
            .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
        }
        btnStop.FlatAppearance.MouseOverBackColor = System.Drawing.ColorTranslator.FromHtml("#2E3D38")
        btnStop.FlatAppearance.MouseDownBackColor = System.Drawing.ColorTranslator.FromHtml("#1E2925")

        btnClear = New System.Windows.Forms.Button With {
            .Text = "清空对话",
            .Location = New System.Drawing.Point(260, 100),
            .Size = New System.Drawing.Size(100, 35),
            .BackColor = System.Drawing.ColorTranslator.FromHtml("#24302C"),
            .ForeColor = System.Drawing.ColorTranslator.FromHtml("#FAF7F0"),
            .FlatStyle = FlatStyle.Flat,
            .Cursor = Cursors.Hand,
            .Anchor = AnchorStyles.Bottom Or AnchorStyles.Left
        }
        btnClear.FlatAppearance.MouseOverBackColor = System.Drawing.ColorTranslator.FromHtml("#2E3D38")
        btnClear.FlatAppearance.MouseDownBackColor = System.Drawing.ColorTranslator.FromHtml("#1E2925")

        bottomPanel.Controls.Add(btnSend)
        bottomPanel.Controls.Add(btnStop)
        bottomPanel.Controls.Add(btnClear)

        ' 3. 中间聊天区(填充剩余空间)
        txtOutput = New Microsoft.Web.WebView2.WinForms.WebView2 With {
            .Dock = DockStyle.Fill
        }

        ' 事件绑定
        AddHandler btnSend.Click, AddressOf BtnSend_Click
        AddHandler btnStop.Click, AddressOf BtnStop_Click
        AddHandler btnClear.Click, AddressOf BtnClear_Click
        AddHandler txtInput.KeyDown, AddressOf TxtInput_KeyDown

        ' 添加控件到窗体(顺序:先 Fill,再 Top/Bottom)
        Me.Controls.Add(txtOutput)
        Me.Controls.Add(topPanel)
        Me.Controls.Add(bottomPanel)
    End Sub

    ' ===== 自适应:动态设输入框宽度,左右各留 12 像素,永远对称 =====
    Protected Overrides Sub OnResize(e As EventArgs)
        MyBase.OnResize(e)
        If txtInput IsNot Nothing AndAlso bottomPanel IsNot Nothing Then
            Dim w As Integer = bottomPanel.ClientSize.Width - 24
            If w > 0 Then txtInput.Width = w
        End If
    End Sub

    ' ===== 加载模型列表 =====
    Private Async Sub LoadModelsAsync()
        Try
            Dim resp = Await http.GetAsync(BaseUrl & "/api/tags").ConfigureAwait(False)
            resp.EnsureSuccessStatusCode()
            Dim json = Await resp.Content.ReadAsStringAsync().ConfigureAwait(False)
            Using doc = JsonDocument.Parse(json)
                Me.Invoke(Sub() cmbModels.Items.Clear())
                For Each model In doc.RootElement.GetProperty("models").EnumerateArray()
                    Dim name = model.GetProperty("name").GetString()
                    Me.Invoke(Sub() cmbModels.Items.Add(name))
                Next
            End Using

            ' 默认选中 qwen 系列,没有就选第一个
            Me.Invoke(Sub()
                          Dim idx As Integer = -1
                          For i As Integer = 0 To cmbModels.Items.Count - 1
                              If cmbModels.Items(i).ToString().StartsWith("qwen") Then
                                  idx = i
                                  Exit For
                              End If
                          Next
                          If idx < 0 AndAlso cmbModels.Items.Count > 0 Then idx = 0
                          cmbModels.SelectedIndex = idx
                          lblStatus.Text = "已连接"
                          lblStatus.ForeColor = System.Drawing.Color.Green
                      End Sub)
        Catch ex As Exception
            Me.Invoke(Sub()
                          lblStatus.Text = "连接失败: " & ex.Message
                          lblStatus.ForeColor = System.Drawing.Color.Red
                      End Sub)
        End Try
    End Sub

    ' ===== 发送消息 =====
    Private Async Sub BtnSend_Click(sender As Object, e As EventArgs)
        Await SendMessageAsync()
    End Sub

    Private Async Sub TxtInput_KeyDown(sender As Object, e As KeyEventArgs)
        If e.Control AndAlso e.KeyCode = Keys.Enter Then
            e.SuppressKeyPress = True
            Await SendMessageAsync()
        End If
    End Sub

    Private Async Function SendMessageAsync() As Task
        ' 防止重复提交
        If isSending Then Return

        Dim userMsg = txtInput.Text.Trim()
        If String.IsNullOrEmpty(userMsg) Then Return
        If cmbModels.SelectedIndex < 0 Then
            MessageBox.Show("请先选择模型")
            Return
        End If

        ' 立即禁用输入,防止重复提交
        isSending = True
        btnSend.Enabled = False
        btnStop.Enabled = True
        txtInput.Enabled = False

        ' 显示用户消息
        fullMd &= "### 你" & vbCrLf & vbCrLf & userMsg & vbCrLf & vbCrLf & "### AI" & vbCrLf & vbCrLf
        RenderMarkdown(fullMd)

        ' 加入历史
        Dim userEntry As New Dictionary(Of String, String)
        userEntry.Add("role", "user")
        userEntry.Add("content", userMsg)
        history.Add(userEntry)
        txtInput.Clear()

        ' 准备请求
        Dim model = cmbModels.SelectedItem.ToString()
        Dim payload = New With {
            .model = model,
            .messages = history,
            .stream = True
        }
        Dim json = JsonSerializer.Serialize(payload)
        Dim content = New StringContent(json, Encoding.UTF8, "application/json")

        ' 流式读取
        cts = New CancellationTokenSource()

        Try
            Dim req = New HttpRequestMessage(HttpMethod.Post, BaseUrl & "/api/chat") With {
                .Content = content
            }
            Dim resp = Await http.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(False)
            resp.EnsureSuccessStatusCode()

            Dim stream = Await resp.Content.ReadAsStreamAsync(cts.Token).ConfigureAwait(False)
            Dim reader = New StreamReader(stream, Encoding.UTF8)
            Dim aiReply = New StringBuilder()

            Do While Not reader.EndOfStream
                Dim line = Await reader.ReadLineAsync(cts.Token).ConfigureAwait(False)
                If String.IsNullOrEmpty(line) Then Continue Do

                Using doc = JsonDocument.Parse(line)
                    Dim root = doc.RootElement
                    Dim msgElem As JsonElement
                    Dim contentElem As JsonElement
                    If root.TryGetProperty("message", msgElem) AndAlso msgElem.TryGetProperty("content", contentElem) Then
                        Dim token = contentElem.GetString()
                        If token IsNot Nothing Then
                            aiReply.Append(token)

                            ' 节流:最多每 120ms 刷一次界面
                            If DateTime.Now - lastRender > TimeSpan.FromMilliseconds(120) Then
                                lastRender = DateTime.Now
                                Dim snapshot = fullMd & aiReply.ToString()
                                Me.Invoke(Sub() RenderMarkdown(snapshot))
                            End If
                        End If
                    End If

                    Dim doneElem As JsonElement
                    If root.TryGetProperty("done", doneElem) AndAlso doneElem.GetBoolean() Then Exit Do
                End Using
            Loop

            ' 保存 AI 回复到历史
            Dim aiEntry As New Dictionary(Of String, String)
            aiEntry.Add("role", "assistant")
            aiEntry.Add("content", aiReply.ToString())
            history.Add(aiEntry)
            fullMd &= aiReply.ToString() & vbCrLf & vbCrLf
            Me.Invoke(Sub() RenderMarkdown(fullMd))

        Catch ex As OperationCanceledException
            fullMd &= " *[已停止]*" & vbCrLf & vbCrLf
            Me.Invoke(Sub() RenderMarkdown(fullMd))
        Catch ex As Exception
            fullMd &= " **错误: " & ex.Message & "**" & vbCrLf & vbCrLf
            Me.Invoke(Sub() RenderMarkdown(fullMd))
        Finally
            Me.Invoke(Sub()
                          btnSend.Enabled = True
                          btnStop.Enabled = False
                          txtInput.Enabled = True
                          txtInput.Focus()
                      End Sub)
            isSending = False
            If cts IsNot Nothing Then
                cts.Dispose()
                cts = Nothing
            End If
        End Try
    End Function

    ' ===== 停止 =====
    Private Sub BtnStop_Click(sender As Object, e As EventArgs)
        If cts IsNot Nothing Then cts.Cancel()
    End Sub

    ' ===== 清空 =====
    Private Sub BtnClear_Click(sender As Object, e As EventArgs)
        fullMd = ""
        RenderMarkdown("")
        history.Clear()
    End Sub

    ' ===== Markdown 渲染(核心:JS 增量更新,彻底解决跳动) =====
    Private Sub RenderMarkdown(md As String)
        If Not isWebViewReady Then Return

        Dim body = Markdown.ToHtml(md, New MarkdownPipelineBuilder().UseAdvancedExtensions().Build())

        ' 转义 JS 字符串中的特殊字符,防止注入报错
        Dim safeBody = body.Replace("\", "\\").Replace("'", "\'").Replace(vbCrLf, "\n").Replace(vbCr, "\n").Replace(vbLf, "\n")

        ' 使用 requestAnimationFrame 确保在浏览器下一帧渲染时滚动,时序最稳
        Dim js = $"document.getElementById('content').innerHTML = '{safeBody}'; requestAnimationFrame(function(){{ window.scrollTo(0, document.body.scrollHeight); }});"

        txtOutput.ExecuteScriptAsync(js)
    End Sub

    ' ===== 关闭时清理 =====
    Protected Overrides Sub OnFormClosing(e As FormClosingEventArgs)
        If cts IsNot Nothing Then cts.Cancel()
        If http IsNot Nothing Then http.Dispose()
        MyBase.OnFormClosing(e)
    End Sub
End Class

六、注意事项(重点避坑)

6.1 控件与布局类

  1. 同一个控件绝不能 Add 进两个父容器。txtInput 只能加到 bottomPanel 一处;早期版本又套了一层 inputPanel 再 Add 两遍,运行时会抛「控件已有父容器」异常,界面卡在初始化——这是「滚动条一直出不来」的真凶之一。
  2. 不要在 Dock 固定高度的容器里同时 Anchor Top + Bottom。WinForms 会按「到上下边距不变」重算高度,把输入框压到 0,滚动条随之消失。输入框高度固定、Anchor 只留 Top|Left,宽度交给 OnResize。
  3. 不要硬编码宽度(如 860)。一旦最大化,右边距就和左边距不一致(一边宽一边窄)。统一由 OnResize 按「客户区宽 - 24」计算。
  4. RichTextBox 没有 Multiline 属性(默认多行)。若残留 txtInput.Multiline = True 会编译报错,进而让你跑到旧版 exe,误以为「改了没反应」。
  5. 想让滚动条始终占位(哪怕没内容也显示),用 RichTextBoxScrollBars.ForcedVertical;按需显示用 Vertical。

6.2 编译与「改了没生效」

  1. 改完务必 生成 → 清理解决方案 → 重新生成解决方案,再 F5。有编译错误时 F5 跑的往往是上一次成功的旧 exe。
  2. 怀疑改没生效时做「变色自证」:把背景色临时改成亮色(如 #FF00FF),重新生成后看是否变样;没变就说明你运行的不是这份代码(多 Form / 改到备份文件 / 启动项目不对)。

6.3 网络与异步

  1. HttpClient 全局复用一个,不要每次请求都 new(会端口耗尽)。
  2. 后台线程刷新 UI 必须 Me.Invoke(Sub() ...),否则跨线程操作控件抛异常。
  3. 流式循环里对 message、content、done 一律用 TryGetProperty 判存在,避免最后一行缺字段崩溃。
  4. e.SuppressKeyPress = True 用于拦截 Ctrl+Enter,否则回车会往输入框多插一个换行。

6.4 运行前置

  1. 必须先启动 Ollama 且已 pull 至少一个模型,否则模型列表为空、发送报连接失败。
  2. 目标机需要 WebView2 Runtime。

七、编译运行步骤

  1. 安装 Ollama,ollama pull 至少一个模型。
  2. Visual Studio 新建 VB WinForms (.NET Framework) 项目。
  3. NuGet 安装 Markdig、Microsoft.Web.WebView2。
  4. 用第五节源代码覆盖 ChatForm.vb,并把启动窗体设为 ChatForm(删除默认 Form1 的启动引用)。
  5. 清理 → 重新生成 → F5。窗口标题为「Ollama 本地聊天」,状态显示「已连接」即成功。
  6. 选模型、输入问题、Ctrl+Enter 发送;点「停止」可中断;点「清空对话」重置。
posted @ 2026-11-22 22:11  deeplogic  阅读(4)  评论(0)    收藏  举报