GPT 很強大,但它不再提供免費的 API——至少不再提供。幸運的是,Google 做到了,透過 Gemini API 和 Studio AI(Google 版本的 ChatGPT)。
在撰寫本文時,Gemini API 免費層提供的功能如下:
如您所見,這足以開始使用 API,因此沒有理由不將其整合到我們的專案中。
他們的快速入門指南非常簡單。
就我而言,我使用 Gemini 來完成一項毫無意義的任務,但目標是展示整合其 API 是多麼容易。
查看以下程式碼片段,它根據受歡迎程度產生「有趣的引言」。
const { GoogleGenerativeAI } = require("@google/generative-ai"); const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const popularity = 42; const prompt = `Write a funny quote, under 200 characters, about popularity on a scale from 0 to 100, where 0 is the least popular and 100 is the most. The quote should describe someone at ${popularity}.`; const result = await model.generateContent(prompt); console.log(result);
輸出:
他的受歡迎程度排在 42 分。不太“酷”,但絕對不是“那個沒人說話的人。”
就是這樣!有幾點要注意:
在我之前的文章《TensorFlow:從 Python 到 JavaScript》中,我分享了一個預測 Twitter 帳戶受歡迎程度的演示。請隨意查看,如果您單擊“推文我的結果”,它將使用上面的程式碼片段產生一條推文。
您可以在這裡找到原始碼
此外,Google 還提供 Studio AI,它與 ChatGPT 類似,但具有一個有趣的功能:取得程式碼。您可以輸入提示,如果這是您想要的服務,只需單擊按鈕,它就會為您提供從您自己的程式碼運行相同提示所需的程式碼。
我是 ChatGPT 的忠實粉絲,但作為一名開發人員,我發現 Studio AI 的免費套餐超級有用。對於實驗來說,OpenAI 並不太貴,但沒有什麼比免費套餐更好的了。兩者都有可靠的文件。
以我的拙見,GPT 仍然比 Gemini 提供更好的答案,但在專案的早期階段,我會選擇 Gemini,並在準確性變得至關重要並且投資有意義時切換到 GPT。
同時,我會遵循代理模式,因此如果需要切換,這是一項簡單的任務。
讓我們來看看下面的程式碼片段:
const { GoogleGenerativeAI } = require("@google/generative-ai"); async function getJokeFromGenerativeAI() { const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const popularity = 42; const prompt = `Write a funny quote, under 200 characters, about popularity on a scale from 0 to 100, where 0 is the least popular and 100 is the most. The quote should describe someone at ${popularity}.`; const result = await model.generateContent(prompt); return result; } // proxy async function getJoke() { const joke = await getJokeFromGenerativeAI(); return joke; }
這樣,消費者就可以呼叫 getJoke(),而不必擔心幕後發生的事情。隨著時間的推移,假設需要 GPT,改變變得簡單:
const OpenAI = require("openai"); async function getJokeFromOpenAI() { const openai = new OpenAI(); const popularity = 42; const prompt = `Write a funny quote, under 200 characters, about popularity on a scale from 0 to 100, where 0 is the least popular and 100 is the most. The quote should describe someone at ${popularity}.`; const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: prompt }], }); return completion.choices[0].message; } // proxy async function getJoke() { const joke = await getJokeFromOpenAI(); return joke; }
注意 getJoke 現在如何呼叫新方法:getJokeFromOpenAI。由於這兩種方法都遵循相同的約定 - 它們都傳回一個解析為字串的 Promise - getJoke 的使用者不會注意到更改,也不需要更新任何內容。
OpenAI 文件
每天,越來越多的應用程式正在整合人工智慧,以至於用戶開始期待它,就像他們期待快速且用戶友好的網站一樣。作為開發人員,了解現有的選項非常重要:自訂模型、開源模型和私有模型,並利用它們來發揮我們的優勢。誰知道接下來會發生什麼,但無論是什麼,它肯定會建立在人工智慧的肩膀上。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3