OpenAI API VBA 函数返回#Value!但MsgBox显示响应

问题描述 投票:0回答:1

我正在尝试将 OpenAI API 集成到 Excel 中。 OpenAI 聊天完成的 http 请求工作正常,响应正常。当我用 MsgBox 显示它时,它看起来很好。

但是当在sheet中调用该函数时,返回值是#VALUE!

Public Function GPT(InputPrompt) As String
  'Define variables
  Dim request As Object
  Dim text, response, API, api_key, DisplayText, GPTModel As String
  Dim GPTTemp As Double
  Dim startPos As Long
  Dim rng As Range
  Dim httpRequest As Object
  Dim countArray As Variant

 
  'API Info
  API = "https://api.openai.com/v1/chat/completions"
  api_key = Trim(Range("API_Key").value)
  'Note: for future upgrades, please replace with GPT-4 etc
  GPTModel = Range("Model_Number").value
  
  If api_key = "" Then 'API key is missing!
    MsgBox "Error: API cannot be blank! Please go to 'Configuration' tab and enter a valid OpenAI API key", vbExclamation, "GPT for Excel"
    frmStatus.Hide
    Exit Function
  End If
    
  'Clean input text and make JSON safe
  text = CleanInput(InputPrompt)
  
  'Create request object
  Set httpRequest = CreateObject("MSXML2.XMLHTTP")
  'Set httpRequest = New MSXML2.XMLHTTP60
  
  'Get temp from Config panel
  GPTTemp = Range("GPT_temperature").value
  
  'Assemble request body
  Dim requestBody As String
  requestBody = "{""model"": ""gpt-4"", ""messages"": [{""role"": ""user"", ""content"": """ & text & """}], ""temperature"": 0.7}"

  With httpRequest
     .Open "POST", API, False
     .setRequestHeader "Content-Type", "application/json"
     .setRequestHeader "Authorization", "Bearer " & api_key
     .send (requestBody)
  End With

  If httpRequest.Status = 200 Then 'Successfully called OpenAI API
   response = httpRequest.responseText
   'Get usage info from response object
   countArr = ExtractUsageInfo(response)
    
   startPos = InStr(response, """content"":") + Len("""content"":") + 2
   endPos = InStr(startPos, response, "},")
   DisplayText = Trim(Mid(response, startPos, endPos - startPos))
   DisplayText = Mid(DisplayText, 1, Len(DisplayText) - 2)
   DisplayText = CleanOutput(DisplayText)
    
   Set request = Nothing
   If FillActive = False Then frmStatus.Hide
   MsgBox (GPT)
   GPT = DisplayText
   MsgBox (GPT)
   If Range("Log_Data").value = "Yes" Then
    Call UpdateLogFile(countArr)
   End If
  Exit Function

End Function
excel vba openai-api worksheet-function
1个回答
0
投票

您在自定义工作表功能中可以执行的操作受到限制。虽然我在 MS Docs 中找不到关于进行 Web 或 API 调用的明确参考,但我对工作表函数的经验让我对这不起作用并不感到惊讶。

另一种方法是将按钮或形状添加到工作表中,然后将该按钮与

Sub
相关联,例如

Sub ButtonClicked()
    Dim Response As String, InputPrompt As String
    InputPrompt = CStr(ThisWorkbook.Sheets("Sheet1").Range("A1").Value)
    Response = GPT(InputPrompt)
    ThisWorkbook.Sheets("Sheet1").Range("A2").Value = Response
End Sub

它使用现有的

GPT
函数来获取单元格 A1 中文本的响应并将其加载到单元格 A2 中(在本例中都在“Sheet1”中......显然您可以根据需要更改单元格和工作表)。

© www.soinside.com 2019 - 2024. All rights reserved.