Sub ChatItem()
'Declare variables
Dim request As Object
Dim response As String
Dim url As String
Dim headers As Object
Dim body As Object
'Set url and headers for API call
url = "https://api.openai.com/v1/engines/chatgpt/completions"
Set headers = CreateObject("Scripting.Dictionary")
headers.Add "Authorization", "sk-xxxxxxxxxxxxxxxx" 'Replace with your API key
'Set body for API call with prompt and parameters
Set body = CreateObject("Scripting.Dictionary")
'Get item name from cell A1
Dim item As String
item = Range("A1").Value
'Set prompt to chat about the item using ChatGPT's persona
body.Add "prompt", "The following is a conversation with ChatGPT, an AI assistant that can help you with Excel tasks. ChatGPT knows how to use VBA and can generate code snippets for you.\n\nHuman: Hi, I want to chat about " & item & ".\nChatGPT:"
'Set parameters for completion such as temperature, max_tokens, etc.
body.Add "temperature", 0.5 'Lower temperature means more predictable responses
body.Add "max_tokens", 50 'Maximum number of tokens to generate
body.Add "stop", "\nHuman:" 'Stop generating when encountering this sequence
'Create a new request object
Set request = CreateObject("MSXML2.XMLHTTP")
'Send a POST request with the url, headers and body as JSON string
request.Open "POST", url, False
For Each Key In headers.keys
request.setRequestHeader Key, headers(Key)
Next Key
request.send JsonConverter.ConvertToJson(body)
'Get the response text as JSON object and extract the generated text
response = request.responseText
Set json = JsonConverter.ParseJson(response)
Dim generated_text As String
generated_text = json("choices")(1)("text")
End Sub
No comments:
Post a Comment