当前位置:首页|资讯|ChatGPT|编程

word 宏关于chatGPT API接口异常返回

作者:达到法定发布时间:2023-04-04

代码参考up主小卫是David

使用效果,API请求异常后,返回报错提醒




Sub chatGPT()

'

' chatGPT 宏

'

'


    Dim selectedText As String

    Dim apiKey As String

    Dim response As Object, re As String

    Dim midString As String

    Dim ans As String

    

    On Error GoTo ErrorHandler

    

    If Selection.Type = wdSelectionNormal Then

        selectedText = Selection.Text

        selectedText = Replace(selectedText, ChrW$(13), "")

        

        apiKey = "your_api_key"

        URL = "https://api.openai.com/v1/chat/completions"

        

        Set response = CreateObject("MSXML2.XMLHTTP")

        response.Open "POST", URL, False

        response.setRequestHeader "Content-Type", "application/json"

        response.setRequestHeader "Authorization", "Bearer " + apiKey

        response.Send "{""model"":""gpt-3.5-turbo"", ""messages"":[{""role"":""user"",""content"":""" & selectedText & """}],""temperature"":0.7}"

        

        If response.Status = 200 And Len(response.responseText) > 0 Then

            re = response.responseText

            midString = Mid(re, InStr(re, """content"":""") + 11)

            ans = Split(midString, """")(0)

            ans = Replace(ans, "\n", "")

            Selection.Text = selectedText & vbNewLine & ans

        Else

            MsgBox "请求失败,响应内容为:" & vbNewLine & response.responseText, vbExclamation, "请求失败"

        End If

        

    Else

        Exit Sub

        

    End If

    

    Exit Sub

    

ErrorHandler:

    MsgBox "发生错误:" & Err.Description, vbCritical, "运行时错误"

    

End Sub



Copyright © 2024 aigcdaily.cn  北京智识时代科技有限公司  版权所有  京ICP备2023006237号-1