prompt = """ Consideration proudct : 工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具 1. Compose human readable product title used on Amazon in english within 20 words. 2. Write 5 selling points for the products in Amazon. 3. Evaluate a price range for this product in U.S. Output the result in json format with three properties called title, selling_points and price_range """
{ "title": "Glow-in-the-Dark Inflatable PVC Frog Night Market Hot Selling Water Toy for Kids", "selling_points": [ "Made of durable PVC material", "Glow-in-the-dark design for night play", "Inflatable design for easy storage and transport", "Perfect for water play and outdoor activities", "Great gift for kids" ], "price_range": "$10 - $20" }
Sub CopyFirstColumnToSecondColumn() '获取第一列和第二列的范围 Dim firstColumn As Range Dim secondColumn As Range Set firstColumn = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row) Set secondColumn = Range("B1:B" & Cells(Rows.Count, 1).End(xlUp).Row) '复制第一列到第二列 secondColumn.Value = firstColumn.Value End Sub
根据ChatGPT给出的详细操作步骤,我们可以通过快捷键 ALT + F11 打开Excel下的VBA编辑器,然后把对应的Excel代码复制进去;也能够在Excel的表格界面里,通过快捷键 ALT + F8 唤起宏的对话框,执行这段宏。你可以试一下,这段VBA的宏的确能够将我们表格里面的第一列,复制到第二列里面。
请为我写这样一段在Excel里面运行的VBA程序: 1. 读取表格里面的第一列的内容 2. 内容的每一行,都是一个商品标题。对这个商品标题,通过下面的Prompt,调用OpenAI的API拿到返回结果: """ Consideration proudct : 商品标题 1. Compose human readable product title used on Amazon in english within 20 words. 2. Write 5 selling points for the products in Amazon. 3. Evaluate a price range for this product in U.S. Output the result in json format with three properties called title, selling_points and price_range """ 3. 将对应API的返回结果,插入到表格的第二列里
Option Explicit Sub GetOpenAIResults() 'Declare variables Dim wb As Workbook Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim productTitle As String Dim sellingPoints As String Dim priceRange As String Dim outputJSON As String Dim response As String Dim request As Object Dim url As String Dim apiKey As String 'Set variables Set wb = ThisWorkbook Set ws = wb.ActiveSheet lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row apiKey = "YOUR_OPENAI_API_KEY" url = "https://api.openai.com/v1/engines/davinci-codex/completions" 'Loop through each row in column A For i = 1 To lastRow 'Get the product title from column A productTitle = ws.Cells(i, 1).Value 'Set up the OpenAI API request Set request = CreateObject("MSXML2.XMLHTTP") request.Open "POST", url, False request.setRequestHeader "Content-Type", "application/json" request.setRequestHeader "Authorization", "Bearer " & apiKey 'Send the request to OpenAI API request.send "{""prompt"": ""Consideration proudct : " & productTitle & vbNewLine & "1. Compose human readable product title used on Amazon in english within 20 words." & vbNewLine & "2. Write 5 selling points for the products in Amazon." & vbNewLine & "3. Evaluate a price range for this product in U.S." & vbNewLine & vbNewLine & "Output the result in json format with three properties called title, selling_points and price_range"",""temperature"": 0.7,""max_tokens"": 1024}" 'Get the response from OpenAI API response = request.responseText 'Extract the title, selling points, and price rangefrom the response productTitle = ExtractJSONValue(response, "title") sellingPoints = ExtractJSONValue(response, "selling_points") priceRange = ExtractJSONValue(response, "price_range") 'Create the JSON output string outputJSON = "{""title"": """ & productTitle & """,""selling_points"": """ & sellingPoints & """,""price_range"": """ & priceRange & """}" 'Insert the JSON output into column B ws.Cells(i, 2).Value = outputJSON Next i End Sub Function ExtractJSONValue(jsonString As String, key As String) As String 'Declare variables Dim jsonRegex As Object Dim matchCollection As Object Dim match As Object 'Set variables Set jsonRegex = CreateObject("VBScript.RegExp") jsonRegex.Global = True jsonRegex.Pattern = """" & key & """\s*:\s*""([^""]+)""" Set matchCollection = jsonRegex.Execute(jsonString) 'Check if the key was found in the JSON string If matchCollection.Count > 0 Then Set match = matchCollection(0) ExtractJSONValue = match.SubMatches(0) Else ExtractJSONValue = "" End
{ "error": { "message": "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)", "type": "invalid_request_error", "param": null, "code": null } }
…… 'Send the request to OpenAI API requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & vbNewLine & "1. Compose human readable product title used on Amazon in english within 20 words." & vbNewLine & "2. Write 5 selling points for the products in Amazon." & vbNewLine & "3. Evaluate a price range for this product in U.S." & vbNewLine & vbNewLine & "Output the result in json format with three properties called title, selling_points and price_range"",""temperature"": 0.7,""max_tokens"": 1024}" request.send requestJSON 'Get the response from OpenAI API response = request.responseText …… 'Insert the JSON output into column B ws.Cells(i, 2).Value = outputJSON ws.Cells(i, 3).Value = response ws.Cells(i, 4).Value = requestJSON ……
{"prompt": "Consideration proudct : 工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具 1. Compose human readable product title used on Amazon in english within 20 words. 2. Write 5 selling points for the products in Amazon. 3. Evaluate a price range for this product in U.S.
Output the result in json format with three properties called title, selling_points and price_range","temperature": 0.7,"max_tokens": 1024}
…… 'Send the request to OpenAI API requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & vbNewLine & "1. Compose human readable product title used on Amazon in english within 20 words." & vbNewLine & "2. Write 5 selling points for the products in Amazon." & vbNewLine & "3. Evaluate a price range for this product in U.S." & vbNewLine & vbNewLine & "Output the result in json format with three properties called title, selling_points and price_range"",""temperature"": 0.7,""max_tokens"": 1024}" requestJSON = "{""prompt"": ""How are you?""}" request.send requestJSON 'Get the response from OpenAI API response = request.responseText ……
{"id":"cmpl-70ZEVctFduMnv6D1WIz4iffTZdaGl","object":"text_completion","created":1680369791,"model":"text-davinci-003","choices":[{"text":"\n\nI'm doing well, thanks for asking!","index":0,"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":4,"completion_tokens":11,"total_tokens":15}}
不过这个返回内容,针对的还是我们刚才构造的最简单的Prompt:“How are you?”的回答,我们把使用的JSON切换回去,再运行一下,看看结果是怎么样的。
1 2 3 4 5 6 7
…… 'Send the request to OpenAI API requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & vbNewLine & "1. Compose human readable product title used on Amazon in english within 20 words." & vbNewLine & "2. Write 5 selling points for the products in Amazon." & vbNewLine & "3. Evaluate a price range for this product in U.S." & vbNewLine & vbNewLine & "Output the result in json format with three properties called title, selling_points and price_range"",""temperature"": 0.7,""max_tokens"": 1024}" request.send requestJSON 'Get the response from OpenAI API response = request.responseText ……
不幸的是,这一次我们还是拿到了一段和之前相同的报错,告诉我们JSON的格式解析不了。
1 2 3 4 5 6 7 8
{ "error": { "message": "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)", "type": "invalid_request_error", "param": null, "code": null } }
…… 'Send the request to OpenAI API requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & vbNewLine & "1. Compose human readable product title used on Amazon in english within 20 words." & vbNewLine & "2. Write 5 selling points for the products in Amazon." & vbNewLine & "3. Evaluate a price range for this product in U.S." & vbNewLine & vbNewLine & "Output the result in json format with three properties called title, selling_points and price_range"",""temperature"": 0.7,""max_tokens"": 1024}" requestJSON = "{""prompt"": ""Consideration proudct : 工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具\r\n1. Compose human readable product title used on Amazon in english within 20 words.\r\n2. Write 5 selling points for the products in Amazon.\r\n3. Evaluate a price range for this product in U.S.\r\n\r\nOutput the result in json format with three properties called title, selling_points and price_range""}" request.send requestJSON 'Get the response from OpenAI API response = request.responseText ……
…… requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & "\r\n1. Compose human readable product title used on Amazon in english within 20 words.\r\n2. Write 5 selling points for the products in Amazon.\r\n3. Evaluate a price range for this product in U.S.\r\n\r\nOutput the result in json format with three properties called title, selling_points and price_range.\r\n"",""temperature"": 0.7,""max_tokens"": 1024}" request.send requestJSON ……
'Loop through each row in column A For i = 1To lastRow …… Set Json = JsonConverter.ParseJson(response)
'Insert the JSON output into column B ws.Cells(i, 2).Value = Json("choices")(1)("text") ws.Cells(i, 3).Value = response ws.Cells(i, 4).Value = requestJSON
再运行一下,第二列里就是我们想要的JSON了。
1
{ "title": "Glow In The Dark Inflatable PVC Frog Pool Toy For Kids", "selling_points": [ "Made of durable and safe PVC material", "Inflatable and easy to store", "Comes with glow in the dark effect", "Ideal for both outdoor and indoor fun", "Perfect for kids of all ages" ], "price_range": "$8 - $12"}
Sub GetOpenAIResults() 'Declare variables Dim wb As Workbook Dim ws As Worksheet Dim lastRow AsLong Dim i AsLong Dim productTitle AsString Dim response AsString Dim request AsObject Dim url AsString Dim apiKey AsString Dim requestJSON AsString Dim Json AsObject
'Set variables Set wb = ThisWorkbook Set ws = wb.ActiveSheet lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row apiKey = "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" url = "https://api.openai.com/v1/engines/text-davinci-003/completions"
'Loop through each row in column A For i = 2To lastRow 'Get the product title from column A productTitle = ws.Cells(i, 1).Value 'Set up the OpenAI API request Set request = CreateObject("MSXML2.XMLHTTP") request.Open "POST", url, False request.setRequestHeader "Content-Type", "application/json" request.setRequestHeader "Authorization", "Bearer " & apiKey 'Send the request to OpenAI API requestJSON = "{""prompt"": ""Consideration proudct : " & productTitle & "\r\n1. Compose human readable product title used on Amazon in english within 20 words.\r\n2. Write 5 selling points for the products in Amazon.\r\n3. Evaluate a price range for this product in U.S.\r\n\r\nOutput the result in json format with three properties called title, selling_points and price_range.\r\n"",""temperature"": 0.7,""max_tokens"": 1024}" request.send requestJSON 'Get the response from OpenAI API response = request.responseText Set Json = JsonConverter.ParseJson(response) Set Json = JsonConverter.ParseJson(Json("choices")(1)("text"))
'Insert the JSON output into column B ws.Cells(i, 2).Value = Json("title") ws.Cells(i, 3).Value = ConcatenateArrayToString(Json("selling_points")) ws.Cells(i, 4).Value = Json("price_range") Next i EndSub
Function ConcatenateArrayToString(arr) AsString Dim result AsString Dim i AsLong 'Assuming the array is stored in a variable named "arr" For i = 1To5 result = result & arr(i) & vbCrLf 'Use vbCrLf to add a line break after each element Next i 'The "result" variable now contains the concatenated string ConcatenateArrayToString = result EndFunction