DEV Community

codemee
codemee

Posted on

2

在 Office VBA 使用 Open AI API

之前介紹過用 Python 串接 OpenAI 模擬 ChatGPT 聊天機器人, 既然它是走 HTTP POST, 如果你也想在 Office 中加入類似功能, 可以使用 Widnows 平台上的 XmlHttpRequest 物件。以下就是一個簡單的範例:

Sub textcompletion()
    Dim prompt, url, body, api_key
    Dim xmlhttp As Object
    Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
    api_key = "你的金鑰"
    url = "https://api.openai.com/v1/completions"
    prompt = InputBox("請輸入提示文字", "OpenAI Text Completion", "hello")
    body = "{""model"": ""text-davinci-003"",""prompt"":""" & prompt _
             & """,""temperature"":0.7,""max_tokens"":1000}"
    xmlhttp.Open "POST", url, False
    xmlhttp.setRequestHeader "Content-Type", "application/json"
    xmlhttp.setRequestHeader "Authorization", "Bearer " & api_key

    xmlhttp.Send body
    MsgBox (xmlhttp.responseText)
End Sub
Enter fullscreen mode Exit fullscreen mode

其中, open 的第三個參數是是否要以非同步方式執行?false 表示不以非同步方式執行, 也就是會等到取得回應結果才返回。如果需要非同步執行 HTTP 請求, 可以參考這一篇文章的教學

這個測試程式執行結果如下:

輸入提示文字後即可取得回應:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay