ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScript で Generative AI を使用する 5 つの方法

JavaScript で Generative AI を使用する 5 つの方法

WBOY
WBOYオリジナル
2024-07-29 07:13:43680ブラウズ

機械学習と AI 開発は伝統的に 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 ツールを使用できる 5 つの方法を説明します。

クラウドAPI

まだ始めたばかりの場合、特に API を直接使用して OpenAI の GPT モデルや Anthropic の Claude モデルなどの大規模言語モデル (LLM) を使用する予定がある場合は、優れたスタートとなります。

モデルとの対話は、フェッチ呼び出しを 1 回行うだけです。

fetch("https://api.openai.com/v1/chat/completions", {
 body: JSON.stringify({
    "model": "gpt-4o-mini",
    "messages": [
      {
        "role": "system",
        "content": "You are a helpful assistant."
      },
      {
        "role": "user",
        "content": "Who won the world series in 2020?"
      },
      {
        "role": "assistant",
        "content": "The Los Angeles Dodgers won the World Series in 2020."
      },
      {
        "role": "user",
        "content": "Where was it played?"
      }
 ]
  }),
 headers: {
 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    "Content-Type": "application/json"
  },
 method: "POST"
})

実際、OpenAI の「Chat Completions」API は、他の多くのモデル プロバイダーの事実上の標準になっています。 Groq や Together.ai などのプロバイダーは OpenAI 互換性を提供します。つまり、URL を変更するだけで別のプロバイダーに切り替え、別のモデルを選択できます。

他のモデルの使用を検討している場合は、一貫した REST API を使用してオープンソース モデルをホストすることに特化し、プラットフォーム上で一部のモデルを微調整するための API を公開する Replicate のようなプロバイダーもあります。

ドッカー

クラウド API は使い始めるには最適ですが、ユースケースによってはクラウドでホストされるプロバイダーに依存したくない場合もあります。たとえば、Llama 3 8B などのモデルをローカル マシン上で直接明示的に実行したい場合や、Python で記述された Unstructed.io などのオープンソース ライブラリを使用し、ホストされているコンポーネントの料金を支払わずに JavaScript プロジェクト内で使用したい場合があります。 API。

一部のプロジェクトでは、そのため、実行時に HTTP API を公開する Docker コンテナを提供しています。たとえば、次を実行して非構造化 API Docker コンテナを開始できます:

docker run -p 8000:8000 -d --rm --name unstructured-api downloads.unstructured.io/unstructured-io/unstructured-api:latest 
--port 8000 --host 0.0.0.0

コンテナが実行されると、後でベクター データベースに保存するドキュメントをチャンクするために使用できる非構造化 API のローカルホスト バージョンが作成されます。

const form = new FormData();

const buffer = // e.g. `fs.readFileSync('./fileLocation');
const fileName = 'test.txt';

form.append('file', buffer, {
 contentType: 'text/plain',
 name: 'file',
 filename: fileName,
});

const response = await fetch('http://localhost:8000/general/v0/general', { 
 method: 'POST',
 body: form,
 headers: {
 Accept: "application/json",
    "Content-Type": "multipart/form-data"
  },
})

同様に、llama.cpp Docker コンテナまたは Ollama を使用して、Llama 3 などの LLM モデルのローカル API を実行できます。

独自のモデルをトレーニングした ML チームと協力している場合、または Huggingface から任意のモデルをホストして同じ Docker コンテナ アプローチを使用したい場合は、Replicate による cog をチェックアウトすることもできます。 Docker をラップしており、ML モデル用の Docker コンテナを作成するために特別に設計されています。

実行したいタスクの表面積が比較的小さく、構成可能性が制限されている場合、これらはすべてうまく機能します。

JavaScript ネイティブ ライブラリ

これが最も明白な選択肢かもしれませんが、JavaScript または TypeScript でネイティブに記述されたライブラリまたはツールを選択することが最善の選択肢であることに変わりはありません。幸いなことに、このエコシステムは成長し続けています。

ほとんどのクラウド API モデル プロバイダーは、JavaScript ネイティブ SDK を提供しています。 OpenAI、Anthropic、Google。

さらに、最も人気のある 2 つのオープンソース LLM フレームワークである Langchain と LlamaIndex は、フレームワークの TypeScript バージョンを提供しています。 Vercel は、LLM とそれが推進するフロントエンド エクスペリエンスを統合することに重点を置いてゼロから構築された AI SDK も提供しています。ドキュメントは Vercel 独自の Next.js フレームワークに重点を置いていますが、SDK は他のフレームワークでも動作します。

import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';

const { text } = await generateText({
 model: openai('gpt-4o'),
 prompt: 'Write a vegetarian lasagna recipe for 4 people.',
});

ただし、これらのほとんどは最終的に他のツールやフレームワークを統合としてラップするため、Python の対応物よりも機能が制限されたままになることがよくあります。たとえば、Python バージョンの Langchain には 18 の異なるドキュメント トランスフォーマー統合があり、JavaScript バージョンには 5 つの異なるドキュメント トランスフォーマー統合があります。

ネイティブ LLM API

これはさらに前向きです。 Google Chrome は最近、ローカルで実行される Gemini Nano モデルへのアクセスを公開する実験的な API セットを Chrome Dev チャネルと Chrome Canary チャネルにリリースしました。

const session = await window.ai.createTextSession();
await session.prompt("Translate the following to German: Hello how are you?")
// " Hallo, wie gehts"

このモデルは、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 で Generative AI を使用する 5 つの方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。