JavaScript에서 Generative AI를 사용하는 5가지 방법

WBOY
풀어 주다: 2024-07-29 07:13:43
원래의
514명이 탐색했습니다.

기계 학습 및 AI 개발은 전통적으로 Python이 지배하고 있기 때문에 튜토리얼, 라이브러리 및 예제 생태계는 주로 Python이 지배합니다. 그러나 AI 엔지니어 개념이 등장하면서 더 많은 풀스택 웹 개발자가 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(대형 언어 모델)을 사용할 계획이라면 훌륭한 시작이 될 수 있습니다.

한 번의 호출만으로 모델과 상호작용할 수 있습니다.

으아악

실제로 OpenAI의 "Chat Completions" API는 다른 많은 모델 제공업체의 사실상 표준이 되었습니다. Groq 또는 Together.ai와 같은 제공업체는 OpenAI 호환성을 제공합니다. 즉, 다른 모델을 선택하려면 URL을 변경하여 다른 제공업체로 전환하면 됩니다.

다른 모델을 사용하려는 경우 일관된 REST API를 사용하여 오픈 소스 모델 호스팅을 전문으로 하고 API를 노출하여 플랫폼에서 일부 모델을 미세 조정하는 Replicate와 같은 제공업체도 있습니다.

도커

클라우드 API는 시작하기에 적합하지만 때로는 사용 사례에 따라 클라우드 호스팅 공급자에 의존하고 싶지 않을 수도 있습니다. 예를 들어 Llama 3 8B와 같은 모델을 로컬 시스템에서 직접 명시적으로 실행하거나 Python으로 작성된 Unstructured.io와 같은 오픈 소스 라이브러리를 사용하고 호스팅 비용을 지불하지 않고 JavaScript 프로젝트 내에서 사용하고 싶을 수 있습니다. API.

이러한 이유로 일부 프로젝트에서는 실행 시 HTTP API를 노출하는 Docker 컨테이너를 제공합니다. 예를 들어 다음을 실행하여 구조화되지 않은 API Docker 컨테이너를 시작할 수 있습니다.

으아악

컨테이너가 실행되면 이제 문서를 청크하여 나중에 벡터 데이터베이스에 저장하는 데 사용할 수 있는 구조화되지 않은 API의 로컬 호스트 버전을 갖게 됩니다.

으아악

마찬가지로 llama.cpp docker 컨테이너나 Ollama를 사용하여 Llama 3과 같은 LLM 모델용 로컬 API를 실행할 수 있습니다.

자체 모델을 교육한 ML 팀과 협력하고 있거나 Huggingface에서 모델을 호스팅하고 동일한 Docker 컨테이너 접근 방식을 사용하려는 경우 cog by Replicate를 확인할 수도 있습니다. 이는 Docker를 래핑하며 ML 모델용 Docker 컨테이너를 생성하도록 특별히 설계되었습니다.

수행하려는 작업의 표면적이 상대적으로 작고 구성 가능성이 제한적인 경우 이 모든 것이 효과적입니다.

JavaScript 네이티브 라이브러리

이제 이것이 가장 확실한 옵션일 수 있지만 최선의 옵션은 기본적으로 JavaScript 또는 TypeScript로 작성된 라이브러리나 도구를 선택하는 것이며 다행히 이 생태계는 계속 성장하고 있습니다.

대부분의 클라우드 API 모델 제공업체는 JavaScript 기본 SDK를 제공합니다. OpenAI, Anthropic 및 Google.

또한 가장 인기 있는 오픈 소스 LLM 프레임워크 중 두 곳인 Langchain과 LlamaIndex는 해당 프레임워크의 TypeScript 버전을 제공합니다. Vercel은 또한 LLM과 LLM이 제공하는 프런트엔드 경험을 결합하는 데 더욱 중점을 두고 처음부터 구축된 ai SDK를 제공합니다. 문서는 Vercel의 자체 Next.js 프레임워크에 중점을 두고 있지만 SDK는 다른 프레임워크에서도 작동합니다.

으아악

그러나 이들 중 대부분은 궁극적으로 다른 도구 및 프레임워크를 통합으로 래핑하기 때문에 여전히 Python에 비해 기능이 더 제한되는 경우가 많습니다. 예를 들어, Langchain의 Python 버전에는 18개의 문서 변환기 통합이 있는 반면 JavaScript 버전에는 5개가 있습니다.

기본 LLM API

이제 이것은 더욱 미래지향적입니다. Google Chrome은 최근 로컬에서 실행되는 Gemini Nano 모델에 대한 액세스를 노출하는 Chrome Dev 및 Chrome Canary 채널에 실험적인 API 세트를 출시했습니다.

으아악

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!