国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術文章
文章詳情頁

使用 .NET MAUI 開發 ChatGPT 客戶端的流程

瀏覽:85日期:2022-06-09 08:58:56
目錄
  • 開發實戰
    • 托盤圖標(右鍵點擊有 menu)
    • WebView
    • 【重點】js 和 csharp 互相調用
    • chatgpt 的開放 api 調用

最近 chatgpt 很火,由于網頁版本限制了 ip,還得必須開代理,用起來比較麻煩,所以我嘗試用 maui 開發一個聊天小應用,結合 chatgpt 的開放 api 來實現(很多客戶端使用網頁版本接口用 cookie 的方式,有很多限制(如下圖)總歸不是很正規)。

效果如下

mac 端由于需要升級 macos13 才能開發調試,這部分我還沒有完成,不過 maui 的控件是跨平臺的,放在后續我升級系統再說。

開發實戰

我是設想開發一個類似 jetbrains 的 ToolBox 應用一樣,啟動程序在桌面右下角出現托盤圖標,點擊圖標彈出應用(風格在 windows mac 平臺保持一致)

需要實現的功能一覽

  • 托盤圖標(右鍵點擊有 menu)
  • webview(js 和 csharp 互相調用)
  • 聊天 SPA 頁面(react 開發,build 后讓 webview 展示)

新建一個 maui 工程(vs2022)

坑一:默認編譯出來的 exe 是直接雙擊打不開的

工程文件加上這個配置

<WindowsPackageType>None</WindowsPackageType><WindowsAppSDKSelfContained Condition=""$(IsUnpackaged)" == "true"">true</WindowsAppSDKSelfContained><SelfContained Condition=""$(IsUnpackaged)" == "true"">true</SelfContained>

以上修改后,編譯出來的 exe 雙擊就可以打開了

托盤圖標(右鍵點擊有 menu)

啟動時設置窗口不能改變大小,隱藏 titlebar, 讓 Webview 控件占滿整個窗口

這里要根據平臺不同實現不同了,windows 平臺采用 winAPI 調用,具體看工程代碼吧!

WebView

在 MainPage.xaml 添加控件

對應的靜態 html 等文件放在工程的 Resource\Raw 文件夾下 (整個文件夾里面默認是作為內嵌資源打包的,工程文件里面的如下配置起的作用)

<!-- Raw Assets (also remove the "Resources\Raw" prefix) --><MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />

【重點】js 和 csharp 互相調用

這部分我找了很多資料,最終參考了這個 demo,然后改進了下。

主要原理是:

  • js 調用 csharp 方法前先把數據存儲在 localstorage 里
  • 然后 windows.location 切換特定的 url 發起調用,返回一個 promise,等待 csharp 的事件
  • csharp 端監聽 webview 的 Navigating 事件,異步進行下面處理
  • 根據 url 解析出來 localstorage 的 key
  • 然后 csharp 端調用 excutescript 根據 key 拿到 localstorage 的 value
  • 進行邏輯處理后返回通過事件分發到 js 端

js 的調用封裝如下:

// 調用csharp的方法封裝export default class CsharpMethod {  constructor(command, data) {    this.RequestPrefix = "request_csharp_";    this.ResponsePrefix = "response_csharp_";    // 唯一    this.dataId = this.RequestPrefix + new Date().getTime();    // 調用csharp的命令    this.command = command;    // 參數    this.data = { command: command, data: !data ? "" : JSON.stringify(data), key: this.dataId }  }   // 調用csharp 返回promise  call() {    // 把data存儲到localstorage中 目的是讓csharp端獲取參數    localStorage.setItem(this.dataId, this.utf8_to_b64(JSON.stringify(this.data)));    let eventKey = this.dataId.replace(this.RequestPrefix, this.ResponsePrefix);    let that = this;    const promise = new Promise(function (resolve, reject) {      const eventHandler = function (e) {window.removeEventListener(eventKey, eventHandler);let resp = e.newValue;if (resp) {  // 從base64轉換  let realData = that.b64_to_utf8(resp);  if (realData.startsWith("err:")) {    reject(realData.substr(4));  } else {    resolve(realData);  }} else {  reject("unknown error :" + eventKey);}      };      // 注冊監聽回調(csharp端處理完發起的)      window.addEventListener(eventKey, eventHandler);    });    // 改變location 發送給csharp端    window.location = "/api/" + this.dataId;    return promise;  }   // 轉成base64 解決中文亂碼  utf8_to_b64(str) {    return window.btoa(unescape(encodeURIComponent(str)));  }  // 從base64轉過來 解決中文亂碼  b64_to_utf8(str) {    return decodeURIComponent(escape(window.atob(str)));  } }

前端的使用方式

import CsharpMethod from "../../services/api" // 發起調用csharp的chat事件函數const method = new CsharpMethod("chat", {msg: message});method.call() // call返回promise.then(data =>{  // 拿到csharp端的返回后展示  onMessageHandler({    message: data,    username: "Robot",    type: "chat_message"  });}).catch(err =>  {    alert(err);});

csharp 端的處理:

這么封裝后,js 和 csharp 的互相調用就很方便了。

chatgpt 的開放 api 調用

注冊好 chatgpt 后可以申請一個 APIKEY。

API 封裝:

  public static async Task<CompletionsResponse> GetResponseDataAsync(string prompt){    // Set up the API URL and API key    string apiUrl = "https://api.openai.com/v1/completions";     // Get the request body JSON    decimal temperature = decimal.Parse(Setting.Temperature, CultureInfo.InvariantCulture);    int maxTokens = int.Parse(Setting.MaxTokens, CultureInfo.InvariantCulture);    string requestBodyJson = GetRequestBodyJson(prompt, temperature, maxTokens);     // Send the API request and get the response data    return await SendApiRequestAsync(apiUrl, Setting.ApiKey, requestBodyJson);} private static string GetRequestBodyJson(string prompt, decimal temperature, int maxTokens){    // Set up the request body    var requestBody = new CompletionsRequestBody    {Model = "text-davinci-003",Prompt = prompt,Temperature = temperature,MaxTokens = maxTokens,TopP = 1.0m,FrequencyPenalty = 0.0m,PresencePenalty = 0.0m,N = 1,Stop = "[END]",    };     // Create a new JsonSerializerOptions object with the IgnoreNullValues and IgnoreReadOnlyProperties properties set to true    var serializerOptions = new JsonSerializerOptions    {IgnoreNullValues = true,IgnoreReadOnlyProperties = true,    };     // Serialize the request body to JSON using the JsonSerializer.Serialize method overload that takes a JsonSerializerOptions parameter    return JsonSerializer.Serialize(requestBody, serializerOptions);} private static async Task<CompletionsResponse> SendApiRequestAsync(string apiUrl, string apiKey, string requestBodyJson){    // Create a new HttpClient for making the API request    using HttpClient client = new HttpClient();     // Set the API key in the request headers    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + apiKey);     // Create a new StringContent object with the JSON payload and the correct content type    StringContent content = new StringContent(requestBodyJson, Encoding.UTF8, "application/json");     // Send the API request and get the response    HttpResponseMessage response = await client.PostAsync(apiUrl, content);     // Deserialize the response    var responseBody = await response.Content.ReadAsStringAsync();     // Return the response data    return JsonSerializer.Deserialize<CompletionsResponse>(responseBody);}

調用方式

 var reply = await ChatService.GetResponseDataAsync("xxxxxxxxxx");

在學習 maui 的過程中,遇到問題我在 Microsoft Learn 提問,回答的效率很快,推薦大家試試看!

到此這篇關于使用 .NET MAUI 開發 ChatGPT 客戶端的文章就介紹到這了,更多相關.NET MAUI 開發 ChatGPT 內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!

標簽: ASP.NET
主站蜘蛛池模板: 一级毛片免费不卡 | 一级床上爽高清播放 | 亚洲日韩视频 | 日本精品久久久久久久久免费 | 色网站在线观看 | 国产91精品一区二区麻豆亚洲 | 日本b站一卡二卡乱码入口 日本s色大片在线观看 | 性欧美视频a毛片在线播放 性欧美一级 | 国产α片 | 亚洲欧美中文日韩在线v日本 | 国产第一区二区三区在线观看 | 欧美全免费aaaaaa特黄在线 | 国产午夜精品理论片免费观看 | 日韩精品免费一区二区 | 午夜一级影院 | 一区二区三区免费视频观看 | 免费va国产高清不卡大片 | ririai99在线视频观看 | 国产亚洲精品激情一区二区三区 | 日本精品在线观看 | 三级中文字幕 | 黄色毛片子 | 成人免费在线观看视频 | 久久99精品久久久久久h | 99久久99热精品免费观看国产 | 久久e| 怡红院免费全部视频在线 | 国产色啪午夜免费视频 | 国产三香港三韩国三级不卡 | 亚洲精品在线播放 | 一区二区三区在线看 | 久久一日本道色综合久久 | 午夜综合| 毛片免费观看日本中文 | 日本免费一区尤物 | 欧美日本一道高清二区三区 | 成人免费影院 | 成人免费xxxxx在线视频 | 国产三级国产精品国产国在线观看 | 俄罗斯极品美女毛片免费播放 | 久久青草国产手机看片福利盒子 |