首頁 > web前端 > js教程 > 主體

在 JavaScript 中使用生成式 AI 的五種方法

WBOY
發布: 2024-07-29 07:13:43
原創
516 人瀏覽過

機器學習和人工智慧開發傳統上由 Python 主導,因此教程、函式庫和範例的生態系統主要由 Python 主導。然而,隨著 AI 工程師概念的興起,我們看到越來越多的全端 Web 開發人員開始從事 AI 工作,隨之而來的是對 JavaScript/Typescript 相容工具的需求上升。事實上,2024 年 2 月,Vercel 的 Jared Palmer 甚至聲稱「未來的 AI 工程師是 TypeScript 工程師」。

Jared Palmer standing in front of a black slide with white text reading

在這篇文章中,我們將介紹作為 JavaScript 開發人員如何在不溫習 Python 技能的情況下使用不同的生成式 AI 工具的五種方法。

雲端API

如果您剛開始,特別是如果您打算使用大型語言模型(LLM),例如 OpenAI 的 GPT 模型或 Anthropic 的 Claude 模型,直接使用其 API 可能是一個很好的開始。

只需一次提取呼叫即可與模型互動。

雷雷

事實上,OpenAI 的「Chat Completions」API 已成為許多其他模型提供者的事實上的標準。 Groq 或 Together.ai 等供應商提供 OpenAI 相容性,這表示您只需更改 URL 即可切換到不同的提供者來選擇不同的模型。

如果您想使用其他模型,還有像 Replicate 這樣的供應商專門提供具有一致的 REST API 的開源模型,甚至公開 API 來微調其平台上的某些模型。

碼頭工人

雖然雲端 API 非常適合入門,但有時您不想依賴雲端託管提供者來滿足您的用例。例如,也許您想直接在本機上明確運行Llama 3 8B 等模型,或者您想使用像Unstructed.io 這樣用Python 編寫的開源庫,並在JavaScript 專案中使用它,而無需支付託管費用API.

出於這個原因,一些專案提供了 Docker 容器,該容器在運行時會公開 HTTP API。例如,您可以透過執行下列命令來啟動非結構化 API Docker 容器:

雷雷

容器運行後,您現在擁有本地主機版本的非結構化 API,您可以使用它對文件進行分塊,以便稍後儲存在向量資料庫中。

雷雷

類似地,您可以使用 llama.cpp docker 容器或 Ollama 為您的 LLM 模型(例如 Llama 3)執行本機 API。

如果您正在與訓練自己模型的 ML 團隊合作,或者您想要在 Huggingface 上託管任何模型並使用相同的 Docker 容器方法,您也可以透過 Replicate 查看 cog。它包裝了 Docker,專為為 ML 模型建立 Docker 容器而設計。

如果您要執行的任務表面積相對較小且可組合性有限,那麼所有這些都非常有用。

JavaScript 原生函式庫

現在這可能是最明顯的選擇,但最好的選擇仍然是選擇一個用 JavaScript 或 TypeScript 原生編寫的函式庫或工具,幸運的是,這個生態系統仍在不斷發展。

大多數雲端 API 模型提供者都提供 JavaScript 本機 SDK,包括。 OpenAI、Anthropic 和 Google。

此外,兩個最受歡迎的開源 LLM 框架 Langchain 和 LlamaIndex 提供了其框架的 TypeScript 版本。 Vercel 還提供從頭開始建立的人工智慧 SDK,更注重將法學碩士及其支援的前端體驗結合在一起。儘管文件主要關注 Vercel 自己的 Next.js 框架,但該 SDK 也適用於其他框架。

雷雷

然而,由於其中大多數最終將其他工具和框架包裝為集成,因此與 Python 工具和框架相比,您通常仍然擁有更多有限的功能。例如,Langchain 的 Python 版本有 18 種不同的文件轉換器集成,而 JavaScript 版本有 5 種。

本地 LLM API

現在這個還是比較有前瞻性的。 Google Chrome 最近在 Chrome Dev 和 Chrome Canary 頻道中發布了一組實驗性 API,可公開對本地運行的 Gemini Nano 模型的存取。

雷雷

由於與最先進的模型(包括 GPT-4o mini 或 Llama 3.1 8B 等較小模型)相比,該模型是如此之小,因此您可能會很難可靠地提示這一點。隨著模型開發的步伐,這種情況可能會很快改變。

While this API is still experimental and only spearheaded by Chrome, the trend of local LLMs might change this quickly as more companies get interested. Mozilla, for example, recently announced that they are focused on moving "local AI" forward incl. creating a new dedicated accelerator program and Apple is already using local models for their new Apple Intelligence feature.

If you want to give the window.ai API a shot, check out Google's explainer repository as well as the chrome-ai package for Vercel's ai SDK to get started.

Pythonia

One interesting approach to using Python tools in JavaScript is pythonia. It's one half of the JSPyBridge project that creates an interface to call JavaScript from Python and Python from JavaScript by facilitating the interprocess communication so that you can write code in the language of your choice.

It uses inter-process communication (IPC) and JavaScript Proxies to enable you to almost use identical code when calling a Python library in JavaScript than in Python and then actually executing it in Python.

For example, here's a code snippet taken from the getting started guide of the Python library haystack-ai:

from haystack import Pipeline, PredefinedPipeline

pipeline = Pipeline.from_template(PredefinedPipeline.CHAT_WITH_WEBSITE)
result = pipeline.run({
    "fetcher": {"urls": ["https://haystack.deepset.ai/overview/quick-start"]},
    "prompt": {"query": "Which components do I need for a RAG pipeline?"}}
)
print(result["llm"]["replies"][0])
登入後複製

By using the pythonia npm package we can write the same equivalent code:

import { python } from "pythonia";

const haystack = await python("haystack");
const { Pipeline, PredefinedPipeline } = await haystack;

const template = await PredefinedPipeline("chat_with_website");
const pipeline = await Pipeline.from_template(template);
const result = await pipeline.run({
 fetcher: { urls: ["https://haystack.deepset.ai/overview/quick-start"] },
 prompt: { query: "Which components do I need for a RAG pipeline?" },
});

console.log((await result.valueOf()).llm.replies[0]);
python.exit();
登入後複製

You might notice that this code is slightly longer and heavily uses await. That's because of the IPC communication. pythonia does a lot of optimizations behind the scenes to effectively communicate between the channels. For example, the actual data is not being sent back from Python to Node.js unless you call valueOf(). However, outside of that the code is very similar and is using native Python libraries.

Performance of pythoia

One concern for you might be performance and while it would be slower than entirely running in Python, the actual performance might surprise you. If you want to use a Python library, like RAGatoille, but the rest of your system is written in JavaScript, really the only alternative to pythonia is exposing the library through an HTTP API and using fetch to bridge the systems.

If we run a benchmark where we use the haystack-ai code snippet from above and run it both using pythonia and expose it using FastAPI, both requests are slow because of their calls to OpenAI but pythonia actually slightly wins the race.

Five ways to use Generative AI in JavaScript

Using `pythonia` results in an average of 13% faster results but both take longer than 1.2s per run

Overall while there is a performance hit of using pythonia over using only native Python, given the long-running nature of most generative AI calls, the overhead becomes relatively negligible especially when compared to making local HTTP requests.

Conclusion

While more and more JavaScript developers are getting into the Generative AI space, we still have ways to go to catch up to an ecosystem that has the breadth of the Python space. Cloud APIs, running local Docker containers, and bridging projects such as pythonia are great options to tap into this space without moving all of your logic into Python. Ultimately it's up to us though to either grow the space of available AI JavaScript tools by contributing to existing open-source projects or even starting new ones if you want to maintain a project. In the meantime, AI tools such as GitHub Copilot, Cursor, or Codeium can help you with writing some Python code.

以上是在 JavaScript 中使用生成式 AI 的五種方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!