在Excel中用GPT-4模型批量调用ChatGPT
马老师几个月前发文介绍了利用ChatGPT的API在Excel中通过VBA建立函数调用ChatGPT的方法。最近OpenAI取消了付费API用户使用GPT4模型的Waitlist。这样马老师就可以直接调用GPT4进行查询了。
撰写本文的另一个原因是原有的一些completion模型如davinci模型已经被OpenAI标注为Legacy。这样一来我们就不必再考虑使用ChatGPT 3.5和4以外的其他模型。代码也可以做一定的简化。
闲话少说,我们先上代码:
Option Explicit
Public Function chatgpt(ByVal question As String, _
Optional ByVal temperature As Single = 0, _
Optional ByVal maxtoken As Integer = 500, _
Optional ByVal model As String = "gpt-4") As String
Const apiKey As String = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Dim apiEndpoint As String
Dim requestHeaders As String
Dim httpRequest As Object
Dim httpResponse As String
Dim cursor As Long
If temperature > 2 Or temperature < 0 Then chatgpt = "API Error: The 2nd parameter Temperature must be between 0 and 2."
If maxtoken > 1000 Or maxtoken < 50 Then chatgpt = "API Error: The 3rd parameter MaxToken must be between 50 and 1000."
Set httpRequest = CreateObject("MSXML2.XMLHTTP")
If model = "gpt-4" Or model = "gpt-3.5-turbo" Then
apiEndpoint = "https://api.openai.com/v1/chat/completions"
httpRequest.Open "POST", apiEndpoint, False
httpRequest.SetRequestHeader "Content-Type", "application/json"
httpRequest.SetRequestHeader "Authorization", "Bearer " & apiKey
httpRequest.Send "{""model"": """ & model & """,""messages"": [{""role"": ""user"", ""content"": """ & _
question & """}], ""temperature"": " & temperature & "}"
If httpRequest.Status = 200 Then
cursor = InStr(1, httpRequest.responseText, """content" & """: """)
chatgpt = Replace(Replace(Mid(httpRequest.responseText, cursor + 12, InStr(cursor, _
httpRequest.responseText, Chr(34) & vbLf & " }," & vbLf) - cursor - 12), "\n", vbCrLf), "\" & Chr(34), Chr(34))
Else
chatgpt = "API Error: " & httpRequest.responseText
End If
Else
chatgpt = "API Error: Model must be " & """gpt-4" & """or " & """gpt-3.5-turbo" & """."
End If
End Function
注意事项:
- 这个代码你可以放入你personal.xlsb文件中,也可以如上图放入一个新建或已有的module中。在打马赛克处填入自己的API Key。
- 马老师因为用的是MSXML2.XMLHTTP,未作超时处理,请在大范围使用前先进行试跑。
- 该UDF(User Defined Function)支持几个参数。
- question – 即prompt。你可以用Excel自由发挥,一些基础的Concat函数不需要马老师再介绍了吧。
- temperature – 决定回答的发散程度或者创意程度。如果希望中规中矩的答案可以设定小一点。合法值在0-2之间。感觉越高花费时间越长。
- maxtoken – 返回最大的token上限。这也决定会不会超时。为了让大家不浪费$$$,现有的代码的合法值在50-1000之间。你可以在官方的计算器中测试大概文本长度所对应的Token数。
https://platform.openai.com/tokenizer - model – 模型。现在该值只有两个合法值,分别是gpt-3.5-turbo和gpt-4。默认是gpt-4。
- 请注意gpt-4的成本比gpt-3要高许多。输入20倍,输出30倍。总之,省着用。课长请忽略。
- 最后,你还是需要全局科学上网来调用API,除非假设中继服务器。
马老师仅测试了Windows环境,如果Mac也能跑请告知。也可以告诉我怎么改,我会分享给其他读者。展示下效果:
对了,跑完了别忘了把单元格复制粘贴成值。这样就不会反复调用浪费$$$了。