溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么將ChatGPT整合到Word中

發(fā)布時間:2023-02-23 10:28:34 來源:億速云 閱讀:1350 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“怎么將ChatGPT整合到Word中”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“怎么將ChatGPT整合到Word中”文章能幫助大家解決問題。

    引言

    自ChatGPT出現(xiàn),各種基于它的軟件擴(kuò)展紛至沓來,目前Word支持ChatGPT的add-in有兩款,可以通過:

    插入->獲取加載項(xiàng)->搜索openai查看。

    其中Ghostwriter從介紹上看功能比較單一,而且軟件需要購買,用自己的API-key,意味著調(diào)用API還要單獨(dú)出錢。

    怎么將ChatGPT整合到Word中

    第二個,軟件似乎是免費(fèi)的,應(yīng)該也是用自己的API-key。從介紹的視頻上看符合使用的預(yù)期,可以發(fā)送選取的文字到ChatGPT,并結(jié)合預(yù)設(shè)的prompt信息返回所需功能,但是安全性未知。

    怎么將ChatGPT整合到Word中

    怎么將ChatGPT整合到Word中

    這類軟件實(shí)際上是將內(nèi)容發(fā)送到OpenAI的服務(wù)器,并將獲取返回內(nèi)容呈現(xiàn),于是產(chǎn)生了使用VBA在Word中整合ChatGPT的想法。雖然使用其他語言(比如python)調(diào)用API更加方便快捷,但VBA對內(nèi)容的操作更直接。

    需求

    使用ChatGPT修改語言時,需要將文本復(fù)制到網(wǎng)頁版的chatGPT中。省掉復(fù)制粘貼的過程,能提升效率。設(shè)想有以下需求:

    基本需求(已實(shí)現(xiàn))

    • 對選取的文字進(jìn)行操作,包括修改語言,翻譯,檢查語法錯誤等

    • 可以選擇不同的模型

    • 用自己的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í)現(xiàn)的。不過相信微軟的攻城獅正在全力將ChatGPT的功能整合到Office全家桶中。類似這樣個人級別的應(yīng)用,最終會被微軟發(fā)布的新功能淘汰,因此無意投入過多。此項(xiàng)目作為VBA練手,基本需求已滿足,也可以作為微軟發(fā)布新word前的過渡。

    實(shí)現(xiàn)

    一切的前提是有openAI的賬號并且綁定了付款方式。新注冊的賬號有$18自動到賬,因此無需綁定付款方式也可以調(diào)用。用完之后再決定需不需要單獨(dú)為此付費(fèi)。

    怎么將ChatGPT整合到Word中

    1. API模型選擇和費(fèi)率

    費(fèi)用如下,是按照1k token來算的,可以簡單理解為字?jǐn)?shù),但不完全相同。最新的模型是Davinci,收費(fèi)也是最高的。注意這里的token數(shù)量指的是發(fā)送和返回的token的總和。ChatGPT告訴我6000字的文章,按照常規(guī)算法,會有10W的token。。好像還是網(wǎng)頁版香呀。。

    怎么將ChatGPT整合到Word中

    具體調(diào)用中,使用模型名稱如下。

    怎么將ChatGPT整合到Word中

    他們都是GPT3的模型,就自身使用感受來看,表現(xiàn)最好的還是davinci,它的速度也是最慢的,ada基本不能用,curie和babbage偶爾能用,不過有的時候連語法錯誤都修改不了,翻譯也是各種不通順。

    2.代碼

    2.1.準(zhǔn)備工作

    采用添加宏的方式,首先要添加開發(fā)者選項(xiàng)卡。

    怎么將ChatGPT整合到Word中

    這也不是必須的,因?yàn)榭梢酝ㄟ^快捷鍵Alt+F11直接打開VBA的界面。

    怎么將ChatGPT整合到Word中

    如果只為當(dāng)前的文本添加宏,就在當(dāng)前的project下添加模塊,如果是為所有的word文檔添加宏的話,就在Normal中添加。之后插入模塊,就可以添加VBA的代碼了。

    怎么將ChatGPT整合到Word中

    其次,為了保證之后的代碼正常運(yùn)行,需要添加程序需要用的幾個Reference,它們的意思有點(diǎn)類似于R的library。不同的模塊可以有不同的Reference,可以選擇項(xiàng)目后統(tǒng)一添加。

    怎么將ChatGPT整合到Word中

    再次,由于VB處理起API的信息就很麻煩,這里需要單獨(dú)載入兩個文件,主要是JsonConverter,它能將API返回的文本轉(zhuǎn)化為Dictionary的形式方便提取。如果對正則表達(dá)熟悉的話,完全不需要使用JsonConverter就可獲取到所需信息。 

    怎么將ChatGPT整合到Word中

    這里通過導(dǎo)入文件的形式,將下載到的bas文件導(dǎo)入。另外要注意的是需要使用這個版本的VBA-JSON-2.3.0,否則會報錯。另外Dictionary定義了幾個對象的屬性,也需要導(dǎo)入。

    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。

    怎么將ChatGPT整合到Word中

    此外,body變量可以添加而外的模型參數(shù)比如n, temperature等控制結(jié)果的輸出,具體見API文檔。

    2.3.提取信息

    一眾函數(shù)分別從response的以下字段提取相應(yīng)信息。

    "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下包括了一個字典,就需要使用類似的方式獲?。簉esponse("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í)證明并不好用,會將所選文字刪除并加上提取的文本。并不是哪里不同修訂哪里。

    第二種, append, 是在所選文字后面加入提取的文本,并以藍(lán)色標(biāo)注。

    第三種, replace, 是直接替換所選文本。

    另外,使用量以及費(fèi)用會以對話框的形式出現(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

    建立相應(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)中將這些宏添加成按鈕。

    怎么將ChatGPT整合到Word中

    修改名稱和圖標(biāo)即可。

    怎么將ChatGPT整合到Word中

    4.實(shí)際使用效果

    找了一個改錯題,選取整段文字,點(diǎn)擊按鈕,返回修改好的文字,以及使用信息。

    怎么將ChatGPT整合到Word中

    之后用修改過的文字,測試其他按鍵。

    怎么將ChatGPT整合到Word中

    怎么將ChatGPT整合到Word中

    怎么將ChatGPT整合到Word中

    怎么將ChatGPT整合到Word中

    至此,基本功能實(shí)現(xiàn)。其他的一些功能,比如使用下拉菜單選擇想要的模型,添加輸入框錄入使用組的API-key,添加自定義的按鈕圖案等功能,需要通過XML定制Ribbon內(nèi)容,就不浪費(fèi)時間了。

    關(guān)于“怎么將ChatGPT整合到Word中”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

    向AI問一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI