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 請求, 可以參考這一篇文章的教學

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

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more