Chat GPT in MS Word

 Chat GPT in MS Word

MS Office Word மென்பொருளில் ChatGPT Artificial Intellegence வசதியை ஒருங்கிணைக்க உதவும் கூறி குறியீடு

Code to integrate the ChatGPT Artificial Intelligence feature into MS Office Word software



MS Word – View – macro - give add to shortcut name to your macro -click on create button- copy the highlighted code

Option Explicit

Sub DeleteShortcut()
    Dim DeleteControl As CommandBarControl
    For Each DeleteControl In Application.CommandBars("Text").Controls
       If DeleteControl.Caption = "Ask ChatGPT" Then
          DeleteControl.Delete
       End If
    Next DeleteControl
End Sub

Sub AddToShortcut()
    Dim Bar As CommandBar
    Dim NewControl As CommandBarButton
    Set Bar = Application.CommandBars("Text")
    Set NewControl = Bar.Controls.Add(Type:=msoControlButton, ID:=1, Temporary:=False)
    With NewControl
        .Caption = "Ask ChatGPT"
        .OnAction = "Ask"
        .Style = msoButtonIconAndCaption
    End With
End Sub


Private Sub Ask()

    Dim selection As selection
    Set selection = Application.selection
    Dim selectedText As String
    Dim init_end, new_end As Integer

    selectedText = Replace(selection.text, ChrW$(13), "")
    init_end = CInt(selection.End)

    Dim req As Object
    Set req = CreateObject("WinHttp.WinHttpRequest.5.1")

    req.Open "POST", "https://chatgpt-api.kesarx.repl.co/chat", True
    req.SetRequestHeader "Content-Type", "application/json"
    req.Send "{""message"": """ & selectedText & """}"
    
    req.WaitForResponse
    
    Dim objHTML, objWin As Object
    Set objHTML = CreateObject("HTMLFile")
    Set objWin = objHTML.parentWindow
    objWin.execScript "var data = " & req.ResponseText & ";", "JScript"
    objWin.execScript "var response_msg = data.choices[0].message.content;", "JScript"

    Dim result As String
    result = objWin.response_msg

    new_end = CInt(selection.End)
    selection.Move Unit:=wdCharacter, Count:=init_end - new_end
    selection.Range.InsertAfter Chr(10) & result & Chr(10)
    
End Sub


Private Sub document_open()
    'adds the right-click shortcut when the document opens
    Call AddToShortcut
End Sub

 - paste the code in the macro editor – go to tools – reference of VB editor – save – go to reference – tick Microsoft runtime –ok- save – 

now type a question – right click on it – and choose “Ask ChatGPT”

Alternative Code to Integrate ChatGPT into MS Office Word

Sub chatGPT()

    Dim request As Object
    Dim text As String, response As String, API As String, api_key As String, DisplayText As String, error_result As String
    Dim startPos As Long, status_code As Long
    Dim prompt As String
    Dim selectedText As Range

    'API Info
    API = "https://api.openai.com/v1/chat/completions"
    
    'API Key
 api_key = "sk-xxxxxxxxxxxxxxxxxxxxxxx"

    If api_key = "" Then
        MsgBox "Error: API key is blank!"
        Exit Sub
    End If
    
    ' Prompt the user to select text in the document
    If Selection.Type <> wdSelectionIP Then
        prompt = Trim(Selection.text)
        Set selectedText = Selection.Range
    Else
        MsgBox "Please select some text before running this macro."
        Exit Sub
    End If
        
    'Cleaning
    text = Replace(prompt, Chr(34), Chr(39))
    text = Replace(text, vbLf, "")
    text = Replace(text, vbCr, "")
    text = Replace(text, vbCrLf, "")

    ' Remove selection
    Selection.Collapse

    'Create an HTTP request object
    Set request = CreateObject("MSXML2.XMLHTTP")
    With request
        .Open "POST", API, False
        .setRequestHeader "Content-Type", "application/json"
        .setRequestHeader "Authorization", "Bearer " & api_key
        .send "{""model"": ""gpt-3.5-turbo"",  ""messages"": [{""content"":""" & text & """,""role"":""user""}]," _
             & """temperature"": 1, ""top_p"": 0.7}"
      status_code = .Status
      response = .responseText
    End With

    'Extract content
    If status_code = 200 Then
      DisplayText = ExtractContent(response)
                
    'Insert response text into Word document
    selectedText.InsertAfter vbNewLine & DisplayText

        
    Else
        startPos = InStr(response, """message"": """) + Len("""message"": """)
        endPos = InStr(startPos, response, """")
        If startPos > Len("""message"": """) And endPos > startPos Then
            DisplayText = Mid(response, startPos, endPos - startPos)
        Else
            DisplayText = ""
        End If
        
        'Insert error message into Word document
        EDisplayText = "Error : " & DisplayText
        selectedText.InsertAfter vbNewLine & EDisplayText
        
    End If
    
    
    'Clean up the object
    Set request = Nothing

End Sub


Function ExtractContent(jsonString As String) As String
    Dim startPos As Long
    Dim endPos As Long
    Dim Content As String
    
    startPos = InStr(jsonString, """content"": """) + Len("""content"": """)
    endPos = InStr(startPos, jsonString, "},") - 2
    Content = Mid(jsonString, startPos, endPos - startPos)
    Content = Trim(Replace(Content, "\""", Chr(34)))
        
    Content = Replace(Content, vbCrLf, "")
    Content = Replace(Content, vbLf, "")
    Content = Replace(Content, vbCr, "")
    Content = Replace(Content, "\n", vbCrLf)
     
    If Right(Content, 1) = """" Then
      Content = Left(Content, Len(Content) - 1)
    End If
    
    ExtractContent = Content

End Function

Procedures for using VBA code in MS Word.

  1. Alt+F11 will launch the VBA editor.
  2. To create a new module, select Insert > Module.
  3. Paste the VBA code inside the module.
  4. Change the API Key to your actual API key in api_key.
  5. VBA editor must be closed.
  6. Run the macro by hitting Alt+F8, choosing ChatGPT, and then pressing RUN.

To use ChatGPT-4, change gpt-3.5-turbo with  gpt-4 in the VBA code.

.


கருத்துகள் இல்லை: