如何將ChatGPT整合到Word中
引言
自ChatGPT出現(xiàn),各種基于它的軟件擴展紛至沓來,目前Word支持ChatGPT的add-in有兩款,可以通過:
插入->獲取加載項->搜索openai查看。
其中Ghostwriter從介紹上看功能比較單一,而且軟件需要購買,用自己的API-key,意味著調(diào)用API還要單獨出錢。
第二個,軟件似乎是免費的,應該也是用自己的API-key。從介紹的視頻上看符合使用的預期,可以發(fā)送選取的文字到ChatGPT,并結(jié)合預設(shè)的prompt信息返回所需功能,但是安全性未知。
這類軟件實際上是將內(nèi)容發(fā)送到OpenAI的服務(wù)器,并將獲取返回內(nèi)容呈現(xiàn),于是產(chǎn)生了使用VBA在Word中整合ChatGPT的想法。雖然使用其他語言(比如python)調(diào)用API更加方便快捷,但VBA對內(nèi)容的操作更直接。
需求
使用ChatGPT修改語言時,需要將文本復制到網(wǎng)頁版的chatGPT中。省掉復制粘貼的過程,能提升效率。設(shè)想有以下需求:
基本需求(已實現(xiàn))
- 對選取的文字進行操作,包括修改語言,翻譯,檢查語法錯誤等
- 可以選擇不同的模型
- 用自己的api-key
- token數(shù)目顯示和計費
進階需求(已放棄)
- 提供add-in安裝或者可分享
- 自定義Ribbon的圖標
- 增加Ribbon下拉菜單,實現(xiàn)用戶選擇模型類型
- 增加Ribbon選項,實現(xiàn)用戶提交api-key
作為野生程序猿,花了一下午完成基本需求,進階的內(nèi)容只要花時間是可以實現(xiàn)的。不過相信微軟的攻城獅正在全力將ChatGPT的功能整合到Office全家桶中。類似這樣個人級別的應用,最終會被微軟發(fā)布的新功能淘汰,因此無意投入過多。此項目作為VBA練手,基本需求已滿足,也可以作為微軟發(fā)布新word前的過渡。
實現(xiàn)
一切的前提是有openAI的賬號并且綁定了付款方式。新注冊的賬號有$18自動到賬,因此無需綁定付款方式也可以調(diào)用。用完之后再決定需不需要單獨為此付費。
1. API模型選擇和費率
費用如下,是按照1k token來算的,可以簡單理解為字數(shù),但不完全相同。最新的模型是Davinci,收費也是最高的。注意這里的token數(shù)量指的是發(fā)送和返回的token的總和。ChatGPT告訴我6000字的文章,按照常規(guī)算法,會有10W的token。。好像還是網(wǎng)頁版香呀。。
具體調(diào)用中,使用模型名稱如下。
他們都是GPT3的模型,就自身使用感受來看,表現(xiàn)最好的還是davinci,它的速度也是最慢的,ada基本不能用,curie和babbage偶爾能用,不過有的時候連語法錯誤都修改不了,翻譯也是各種不通順。
2.代碼
2.1.準備工作
采用添加宏的方式,首先要添加開發(fā)者選項卡。
這也不是必須的,因為可以通過快捷鍵Alt+F11直接打開VBA的界面。
如果只為當前的文本添加宏,就在當前的project下添加模塊,如果是為所有的word文檔添加宏的話,就在Normal中添加。之后插入模塊,就可以添加VBA的代碼了。
其次,為了保證之后的代碼正常運行,需要添加程序需要用的幾個Reference,它們的意思有點類似于R的library。不同的模塊可以有不同的Reference,可以選擇項目后統(tǒng)一添加。
再次,由于VB處理起API的信息就很麻煩,這里需要單獨載入兩個文件,主要是JsonConverter,它能將API返回的文本轉(zhuǎn)化為Dictionary的形式方便提取。如果對正則表達熟悉的話,完全不需要使用JsonConverter就可獲取到所需信息。
這里通過導入文件的形式,將下載到的bas文件導入。另外要注意的是需要使用這個版本的VBA-JSON-2.3.0,否則會報錯。另外Dictionary定義了幾個對象的屬性,也需要導入。
2.2. 調(diào)用API
CallOpenAI,該函數(shù)會將word中選取的文字,加上你自己寫的指示,一并提交給OpenAI的模型,函數(shù)返回值response是一個Dictionary,包括了model, choices, usage, created等各種字段。
model的選擇和名稱見上文。
prompt可以是任何指示,比如幫我修改這段文字。(變量名用instruction更合理)。
selectedText是Word文檔中選取的文字。
Function CallOpenAI(model As String, prompt As String, selectedText As String) As Dictionary Dim url As String Dim headers As Object Dim body As Object Dim client As Object Dim response As Object ' Set up the API endpoint URL, headers, and request body url = "https://api.openai.com/v1/completions" Set headers = CreateObject("Scripting.Dictionary") headers.Add "Content-Type", "application/json" headers.Add "Authorization", "Bearer <API_KEY>" Set body = CreateObject("Scripting.Dictionary") body.Add "model", model body.Add "prompt", prompt & "{" & selectedText & "}" body.Add "max_tokens", 1000 ' Send the API request and get the response Set client = CreateObject("MSXML2.XMLHTTP") client.Open "POST", url, False For Each key In headers.Keys client.setRequestHeader key, headers(key) Next client.send JsonConverter.ConvertToJson(body) 'Debug.Print client.responseText ' Parse the response JSON and return the completed text Set response = JsonConverter.ParseJson(client.responseText) Set CallOpenAI = response End Function
這里需要在header變量中添加自己的OpenAI的API-Key,具體而言是在12行將<API_KEY> 替換為自己的API_key。
此外,body變量可以添加而外的模型參數(shù)比如n, temperature等控制結(jié)果的輸出,具體見API文檔。
2.3.提取信息
一眾函數(shù)分別從response的以下字段提取相應信息。
"model"-模型名稱
'usage"-模型使用情況,用了多少個token
”choices"-模型返回的文字信息,這就是ChatGPT的回答。
Function GetModel(response As Dictionary) As String GetModel = response("model") End Function Function GetUsage(response As Dictionary) As Integer GetUsage = response("usage")("total_tokens") End Function Function GetResponseText(response As Dictionary) As String Dim resp As String resp = response("choices")(1)("text") resp = Trim(resp) resp = Replace(resp, vbNewLine, "") 'resp = Replace(resp, "\n\n", "") 'resp = Replace(resp, vbLf, "") 'resp = Replace(resp, vbCrLf, "") 'resp = Replace(resp, Chr(10), "") 'resp = Replace(resp, Chr(13), "") 'resp = Replace(resp, vbCr, "") 'resp = Replace(resp, vbLf, "") GetResponseText = resp End Function
Dictornay的變量中,字典的字典是無法直接獲取的,大部分操作都可能會報錯,用Debug.Print也無法顯示。比如choices下包括了一個字典,就需要使用類似的方式獲取:response("choices")(1)("text")
2.4.計算模型使用費用
有必要根據(jù)模型的名稱和使用量,計算一下使用成本。
Function GetEstimatedFee(model As String, totalTokens As Integer) As Double ' Set the token prices for each model Dim tokenPrices As Object Set tokenPrices = CreateObject("Scripting.Dictionary") tokenPrices.Add "text-davinci-003", 0.02 tokenPrices.Add "text-curie-001", 0.002 tokenPrices.Add "text-babbage-001", 0.0005 ' Calculate the estimated fee Dim tokenPrice As Double If tokenPrices.Exists(model) Then tokenPrice = tokenPrices(model) Else 'Defaultto the davinci token price if the modelisnot recognized tokenPrice = tokenPrices("text-davinci-003") End If GetEstimatedFee = totalTokens * tokenPrice * 0.001 End Function
2.5.返回信息到Word界面
該部分代碼的輸入為,提取到文本(也就是chatGPT給你的答案),費用以及模式。
這里考慮了三種模式:
第一種,track, 是將文本使用修訂的方式放到word中,事實證明并不好用,會將所選文字刪除并加上提取的文本。并不是哪里不同修訂哪里。
第二種, append, 是在所選文字后面加入提取的文本,并以藍色標注。
第三種, replace, 是直接替換所選文本。
另外,使用量以及費用會以對話框的形式出現(xiàn)。
Sub ProcessChatGPTResponse(responseText As String, feeText As String, mode As String) Dim newRange As Range Dim resp As String resp = responseText 'resp = responseText & "**" & feeText ' Get the current selection Dim currentSelection As Range Set currentSelection = Selection.Range ' Determine how to handle the corrected text based on the mode parameter If mode = "track" Then ' Create a new range and insert the corrected text Set newRange = ActiveDocument.Range(currentSelection.End, currentSelection.End) newRange.Text = resp ' Track changes on the new range ActiveDocument.TrackRevisions = True currentSelection.Text = resp ActiveDocument.TrackRevisions = False ElseIf mode = "append" Then Dim insertText As String insertText = vbCr & resp ' Insert the corrected text in a new paragraph after the selection currentSelection.InsertAfter insertText '~~> Remove selection. This will move the cursor at end of selected word Selection.MoveRight Unit:=wdCharacter, Count:=1 '~~> Select the inserted word Selection.MoveRight Unit:=wdCharacter, Count:=Len(insertText), Extend:=wdExtend Selection.Font.Color = wdColorBlue ElseIf mode = "replace" Then ' Replace the selected text with the corrected text currentSelection.Text = resp End If MsgBox "Estimated Cost:" & vbCrLf & feeText, vbInformation, "Estimated Cost" End Sub
3.界面
由于不同的按鈕,目前只是用戶的指示不同,剩下內(nèi)容均一致,所以這里創(chuàng)建了一個函數(shù),簡化后面的流程。輸入是model和prompt。這里統(tǒng)一使用了"append"的顯示方式,即在選取文字之后添加chatGPT回答。
Sub RinbbonFun(model As String, prompt As String) Dim selectedText As String Dim response As Dictionary Dim modelName As String Dim tokenN As Integer Dim feeText As String Dim responseText As String selectedText = Selection.Text Set response = CallOpenAI(model, prompt, selectedText) responseText = GetResponseText(response) modelName = GetModel(response) tokenN = GetUsage(response) EstimatedFee = GetEstimatedFee(modelName, tokenN) feeText = "Model: " & modelName & ", estimated cost: $" & EstimatedFee & "(Tokens:" & tokenN & ")" 'Debug.Print responseText ' Do something with the response, such as replace the selection with the returned text ProcessChatGPTResponse responseText, feeText, "append" End Sub
建立相應的函數(shù),用于不同的按鈕。
Sub ImproveEmail() RinbbonFun "text-davinci-003", "Improve my writing in the email:" End Sub Sub RewordIt() RinbbonFun "text-davinci-003", "Rephrase the following texts and avoid Plagiarism:" End Sub Sub SummarizeIt() RinbbonFun "text-davinci-003", "Summarize the following texts for me:" End Sub Sub Translate2CN() RinbbonFun "text-davinci-003", "Translate the following texts into simplified Chinese:" End Sub Sub Translate2EN() RinbbonFun "text-davinci-003", "Translate the following texts into English:" End Sub Sub ImproveWriting() RinbbonFun "text-davinci-003", "Improve my writing:" End Sub Sub ElaborateIt() RinbbonFun "text-davinci-003", "Elaborate the following content:" End Sub
然后在Ribbon選項中將這些宏添加成按鈕。
修改名稱和圖標即可。
4.實際使用效果
找了一個改錯題,選取整段文字,點擊按鈕,返回修改好的文字,以及使用信息。
之后用修改過的文字,測試其他按鍵。
至此,基本功能實現(xiàn)。其他的一些功能,比如使用下拉菜單選擇想要的模型,添加輸入框錄入使用組的API-key,添加自定義的按鈕圖案等功能,需要通過XML定制Ribbon內(nèi)容,就不浪費時間了。
到此這篇關(guān)于如何將ChatGPT整合到Word中的文章就介紹到這了,更多相關(guān)ChatGPT整合到Word內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VSCode配置Lua開發(fā)環(huán)境的實現(xiàn)示例
本文主要介紹了VSCode配置Lua開發(fā)環(huán)境的實現(xiàn)示例,主要包括下載及配置環(huán)境,具有一定的參考價值,感興趣的可以了解一下2023-09-09詳解DES&3DES算法的原理以及C#和JS的實現(xiàn)
DES?全稱為?Data?Encryption?Standard,即數(shù)據(jù)加密標準,是一種使用密鑰加密的塊算法。3DES?算法通過對?DES?算法進行改進,增加?DES?的密鑰長度來避免類似的攻擊。本文就來聊聊它們的原理與實現(xiàn)吧2023-03-03