如何將ChatGPT整合到Word中
引言
自ChatGPT出現(xiàn),各種基于它的軟件擴(kuò)展紛至沓來,目前Word支持ChatGPT的add-in有兩款,可以通過:
插入->獲取加載項(xiàng)->搜索openai查看。
其中Ghostwriter從介紹上看功能比較單一,而且軟件需要購(gòu)買,用自己的API-key,意味著調(diào)用API還要單獨(dú)出錢。
第二個(gè),軟件似乎是免費(fèi)的,應(yīng)該也是用自己的API-key。從介紹的視頻上看符合使用的預(yù)期,可以發(fā)送選取的文字到ChatGPT,并結(jié)合預(yù)設(shè)的prompt信息返回所需功能,但是安全性未知。
這類軟件實(shí)際上是將內(nèi)容發(fā)送到OpenAI的服務(wù)器,并將獲取返回內(nèi)容呈現(xiàn),于是產(chǎn)生了使用VBA在Word中整合ChatGPT的想法。雖然使用其他語(yǔ)言(比如python)調(diào)用API更加方便快捷,但VBA對(duì)內(nèi)容的操作更直接。
需求
使用ChatGPT修改語(yǔ)言時(shí),需要將文本復(fù)制到網(wǎng)頁(yè)版的chatGPT中。省掉復(fù)制粘貼的過程,能提升效率。設(shè)想有以下需求:
基本需求(已實(shí)現(xiàn))
- 對(duì)選取的文字進(jìn)行操作,包括修改語(yǔ)言,翻譯,檢查語(yǔ)法錯(cuò)誤等
- 可以選擇不同的模型
- 用自己的api-key
- token數(shù)目顯示和計(jì)費(fèi)
進(jìn)階需求(已放棄)
- 提供add-in安裝或者可分享
- 自定義Ribbon的圖標(biāo)
- 增加Ribbon下拉菜單,實(shí)現(xiàn)用戶選擇模型類型
- 增加Ribbon選項(xiàng),實(shí)現(xiàn)用戶提交api-key
作為野生程序猿,花了一下午完成基本需求,進(jìn)階的內(nèi)容只要花時(shí)間是可以實(shí)現(xiàn)的。不過相信微軟的攻城獅正在全力將ChatGPT的功能整合到Office全家桶中。類似這樣個(gè)人級(jí)別的應(yīng)用,最終會(huì)被微軟發(fā)布的新功能淘汰,因此無意投入過多。此項(xiàng)目作為VBA練手,基本需求已滿足,也可以作為微軟發(fā)布新word前的過渡。
實(shí)現(xiàn)
一切的前提是有openAI的賬號(hào)并且綁定了付款方式。新注冊(cè)的賬號(hào)有$18自動(dòng)到賬,因此無需綁定付款方式也可以調(diào)用。用完之后再?zèng)Q定需不需要單獨(dú)為此付費(fèi)。
1. API模型選擇和費(fèi)率
費(fèi)用如下,是按照1k token來算的,可以簡(jiǎn)單理解為字?jǐn)?shù),但不完全相同。最新的模型是Davinci,收費(fèi)也是最高的。注意這里的token數(shù)量指的是發(fā)送和返回的token的總和。ChatGPT告訴我6000字的文章,按照常規(guī)算法,會(huì)有10W的token。。好像還是網(wǎng)頁(yè)版香呀。。
具體調(diào)用中,使用模型名稱如下。
他們都是GPT3的模型,就自身使用感受來看,表現(xiàn)最好的還是davinci,它的速度也是最慢的,ada基本不能用,curie和babbage偶爾能用,不過有的時(shí)候連語(yǔ)法錯(cuò)誤都修改不了,翻譯也是各種不通順。
2.代碼
2.1.準(zhǔn)備工作
采用添加宏的方式,首先要添加開發(fā)者選項(xiàng)卡。
這也不是必須的,因?yàn)榭梢酝ㄟ^快捷鍵Alt+F11直接打開VBA的界面。
如果只為當(dāng)前的文本添加宏,就在當(dāng)前的project下添加模塊,如果是為所有的word文檔添加宏的話,就在Normal中添加。之后插入模塊,就可以添加VBA的代碼了。
其次,為了保證之后的代碼正常運(yùn)行,需要添加程序需要用的幾個(gè)Reference,它們的意思有點(diǎn)類似于R的library。不同的模塊可以有不同的Reference,可以選擇項(xiàng)目后統(tǒng)一添加。
再次,由于VB處理起API的信息就很麻煩,這里需要單獨(dú)載入兩個(gè)文件,主要是JsonConverter,它能將API返回的文本轉(zhuǎn)化為Dictionary的形式方便提取。如果對(duì)正則表達(dá)熟悉的話,完全不需要使用JsonConverter就可獲取到所需信息。
這里通過導(dǎo)入文件的形式,將下載到的bas文件導(dǎo)入。另外要注意的是需要使用這個(gè)版本的VBA-JSON-2.3.0,否則會(huì)報(bào)錯(cuò)。另外Dictionary定義了幾個(gè)對(duì)象的屬性,也需要導(dǎo)入。
2.2. 調(diào)用API
CallOpenAI,該函數(shù)會(huì)將word中選取的文字,加上你自己寫的指示,一并提交給OpenAI的模型,函數(shù)返回值response是一個(gè)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的以下字段提取相應(yīng)信息。
"model"-模型名稱
'usage"-模型使用情況,用了多少個(gè)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的變量中,字典的字典是無法直接獲取的,大部分操作都可能會(huì)報(bào)錯(cuò),用Debug.Print也無法顯示。比如choices下包括了一個(gè)字典,就需要使用類似的方式獲取:response("choices")(1)("text")
2.4.計(jì)算模型使用費(fèi)用
有必要根據(jù)模型的名稱和使用量,計(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給你的答案),費(fèi)用以及模式。
這里考慮了三種模式:
第一種,track, 是將文本使用修訂的方式放到word中,事實(shí)證明并不好用,會(huì)將所選文字刪除并加上提取的文本。并不是哪里不同修訂哪里。
第二種, append, 是在所選文字后面加入提取的文本,并以藍(lán)色標(biāo)注。
第三種, replace, 是直接替換所選文本。
另外,使用量以及費(fèi)用會(huì)以對(duì)話框的形式出現(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)建了一個(gè)函數(shù),簡(jiǎn)化后面的流程。輸入是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
建立相應(yīng)的函數(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選項(xiàng)中將這些宏添加成按鈕。
修改名稱和圖標(biāo)即可。
4.實(shí)際使用效果
找了一個(gè)改錯(cuò)題,選取整段文字,點(diǎn)擊按鈕,返回修改好的文字,以及使用信息。
之后用修改過的文字,測(cè)試其他按鍵。
至此,基本功能實(shí)現(xiàn)。其他的一些功能,比如使用下拉菜單選擇想要的模型,添加輸入框錄入使用組的API-key,添加自定義的按鈕圖案等功能,需要通過XML定制Ribbon內(nèi)容,就不浪費(fèi)時(shí)間了。
到此這篇關(guān)于如何將ChatGPT整合到Word中的文章就介紹到這了,更多相關(guān)ChatGPT整合到Word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VSCode遠(yuǎn)程SSH免密登錄配置實(shí)現(xiàn)
這篇文章主要介紹了VSCode遠(yuǎn)程SSH免密登錄配置實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04關(guān)于Python與Golang語(yǔ)言的對(duì)比分析
這篇文章主要為大家介紹了關(guān)于Python與Golang的語(yǔ)言對(duì)比分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05VSCode配置Lua開發(fā)環(huán)境的實(shí)現(xiàn)示例
本文主要介紹了VSCode配置Lua開發(fā)環(huán)境的實(shí)現(xiàn)示例,主要包括下載及配置環(huán)境,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09詳解DES&3DES算法的原理以及C#和JS的實(shí)現(xiàn)
DES?全稱為?Data?Encryption?Standard,即數(shù)據(jù)加密標(biāo)準(zhǔn),是一種使用密鑰加密的塊算法。3DES?算法通過對(duì)?DES?算法進(jìn)行改進(jìn),增加?DES?的密鑰長(zhǎng)度來避免類似的攻擊。本文就來聊聊它們的原理與實(shí)現(xiàn)吧2023-03-03