Skip to content

AiOllamaChatDemo 项目分析

项目信息

文件结构

AiOllamaChatDemo/
├── Extractor_Icon.ico
├── Project1.py
├── Project1.xml
├── Unit1.py
├── Unit1.pydfm
├── Unit1.sct
├── Unit1.sfm

主程序文件: Project1.py

import sys
from glcl import *
from Unit1 import *

def main():
    Application.Initialize()
    Application.Title = 'Project1'
    Application.MainFormOnTaskbar = True
    Application.Icon.LoadFromFile(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Extractor_Icon.ico"))
    MainForm = Form1(Application)
    MainForm.Show()
    FreeConsole()
    Application.Run()
    MainForm.Free()

if __name__ == '__main__':
    main()

单元文件: Unit1.py

import os
from glcl import *

class Form1(Form):

    def __init__(self, owner):
        self.Button2 = Button(self)
        self.OllamaChat = AiOllamaChat(self)
        self.Button1 = Button(self)
        self.MemoPrompt = Memo(self)
        self.MemoChat = Memo(self)
        self.LoadProps(os.path.join(os.path.dirname(os.path.abspath(__file__)), "Unit1.pydfm"))
        self.Button2.OnClick = self.Button2Click
        self.Button1.OnClick = self.Button1Click
        self.OllamaChat.OnReceiveDataEnd = self.OllamaChatReceiveDataEnd
        self.OllamaChat.OnReceiveData = self.OllamaChatReceiveData
        '''
        使用方法:
        1.网页搜索Ollama运行千问大模型,下载Ollama客户端安装并用命令下载合适的千问大模型
        2.退出右下角Ollama客户端,并在控制台(不要用PowerShell)中运行命令set OLLAMA_HOST=0.0.0.0:11434
        3.上述命令是允许全网段访问,然后再运行命令ollama serve启动服务
        4.Ollama服务开启成功后,点击窗体设计器上的AiOllamaChat控件,属性设置Model为当前模型名
        5.如Ollama运行在本机,则Url属性无需修改,如运行在局域网或远程服务器,则ip需修改
        '''

    def UpdateMemo(self, Text):
        try:
            self.MemoChat.Lines.Text += Text
            self.MemoChat.Perform(EM_LINESCROLL, 0, self.MemoChat.Lines.Count-1)
        finally:
            pass

    # 第一种方式,接收数据结束事件
    def OllamaChatReceiveDataEnd(self, Sender, aMsg, aResponse, aRole, aText):
        self.MemoChat.Lines.Add('') # 换行

    # 第一种方式,接收数据事件
    def OllamaChatReceiveData(self, Sender, aMsg, aResponse, aRole, aText):
        try:
            self.MemoChat.Lines.BeginUpdate()   # 用于防止界面闪烁和提高性能
            self.MemoChat.Text += aText
            self.MemoChat.Perform(EM_LINESCROLL, 0, self.MemoChat.Lines.Count-1)  # 让Memo文本滚动到最底部一行
        finally:
            self.MemoChat.Lines.EndUpdate() # 用于防止界面闪烁和提高性能

    # 第一种方式
    def Button1Click(self, Sender):
          self.UpdateMemo('你 : ' + self.MemoPrompt.Text + '\r\n')
          Msg = self.OllamaChat.NewMessage(self.MemoPrompt.Text, 'user')
          Res = self.OllamaChat.Run(Msg, None)

          self.UpdateMemo('AI : ' + Res)
          self.MemoPrompt.Lines.Clear()

    # 第二种方式
    def Button2Click(self, Sender):
        #self.OllamaChat.Asynchronous = False  # 可以是异步也可以是同步
        self.MemoChat.Text = self.OllamaChat.AddMessageAndRun(self.MemoPrompt.Text, 'user', [])

设计文件: Unit1.sct

def FormClose(Sender, Action): 
def OllamaChatReceiveData(Sender, aMsg, aResponse, aRole, aText): 
def OllamaChatReceiveDataEnd(Sender, aMsg, aResponse, aRole, aText): 
def Button1Click(Sender): 
def FormShow(Sender): 
def Button2Click(Sender): 

设计文件: Unit1.sfm

object Form1: TForm
  Left = 0
  Top = 0
  Caption = 'TAiOllamaChatDemo'
  ClientHeight = 450
  ClientWidth = 645
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -15
  Font.Name = 'Segoe UI'
  Font.Style = []
  TextHeight = 20
  object MemoChat: TMemo
    Left = 16
    Top = 8
    Width = 617
    Height = 201
    TabOrder = 0
  end
  object MemoPrompt: TMemo
    Left = 16
    Top = 224
    Width = 617
    Height = 185
    TabOrder = 1
  end
  object Button1: TButton
    Left = 483
    Top = 416
    Width = 150
    Height = 25
    Caption = #31532#19968#31181#26041#24335
    TabOrder = 2
    OnClick = Button1Click
  end
  object Button2: TButton
    Left = 328
    Top = 416
    Width = 150
    Height = 25
    Caption = #31532#20108#31181#26041#24335
    TabOrder = 3
    OnClick = Button2Click
  end
  object OllamaChat: TAiOllamaChat
    ApiKey = '@OLLAMA_API_KEY'
    Model = 'qwen2:7b'
    Logprobs = False
    Max_tokens = 300
    N = 1
    Response_format = tiaChatRfText
    Seed = 0
    Asynchronous = True
    Temperature = 1.00000000000000000
    Top_p = 1.00000000000000000
    Tool_choice = 'auto'
    Tool_Active = False
    User = 'user'
    InitialInstructions.Strings = (
      'Eres un asistente muy '#40407'il y servicial')
    Prompt_tokens = 0
    Completion_tokens = 0
    Total_tokens = 0
    OnReceiveData = OllamaChatReceiveData
    OnReceiveDataEnd = OllamaChatReceiveDataEnd
    Url = 'http://192.168.1.33:11434/'
    ResponseTimeOut = 350000
    Stream_Usage = False
    NativeInputFiles = []
    NativeOutputFiles = []
    ChatMediaSupports = []
    keep_alive = '1m'
    Left = 288
    Top = 413
  end
end

其他文件

  • Extractor_Icon.ico
  • Project1.xml

详细分析

功能概述

AI聊天功能演示

使用的组件

  • Form1 (TForm)
  • MemoChat (TMemo)
  • MemoPrompt (TMemo)
  • Button1 (TButton)
  • Button2 (TButton)
  • OllamaChat (TAiOllamaChat)

技术特点

  • 包含6个GUI组件
  • 定义2个事件处理

窗体属性

  • caption: #31532#20108#31181#26041#24335
  • height: 450
  • width: 645

代码分析

导入的模块: - import os - from glcl import *

定义的类: - Form1

定义的方法: - init - UpdateMemo - OllamaChatReceiveDataEnd - OllamaChatReceiveData - Button1Click - Button2Click

事件绑定: - self.Button2.OnClick = self.Button2Click - self.Button1.OnClick = self.Button1Click