JavaScript에서 Generative AI를 사용하는 5가지 방법
기계 학습 및 AI 개발은 전통적으로 Python이 지배하고 있기 때문에 튜토리얼, 라이브러리, 예제 생태계는 주로 Python이 지배합니다. 그러나 AI 엔지니어 개념이 등장하면서 더 많은 풀스택 웹 개발자가 AI 작업을 시작하고 있으며, 이와 함께 JavaScript/Typescript 호환 도구에 대한 수요도 증가하고 있습니다. 실제로 2024년 2월 Vercel의 Jared Palmer는 "미래의 AI 엔지니어는 TypeScript 엔지니어이다"라고 주장하기도 했습니다.
이 블로그 게시물에서는 JavaScript 개발자가 Python 기술을 익히지 않고도 다양한 생성 AI 도구를 사용할 수 있는 5가지 방법을 살펴보겠습니다.
클라우드 API
이제 막 시작했다면, 특히 OpenAI의 GPT 모델이나 Anthropic의 Claude 모델과 같은 LLM(대형 언어 모델)을 API를 직접 사용하여 사용할 계획이라면 훌륭한 시작이 될 수 있습니다.
한 번의 호출만으로 모델과 상호작용할 수 있습니다.
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와 같은 제공업체도 있습니다.
도커
Cloud API는 시작하기에 적합하지만 사용 사례에 따라 클라우드 호스팅 제공업체에 의존하고 싶지 않은 경우도 있습니다. 예를 들어 Llama 3 8B와 같은 모델을 로컬 시스템에서 직접 명시적으로 실행하거나 Python으로 작성된 Unstructured.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 컨테이너 접근 방식을 사용하려는 경우 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는 다른 프레임워크에서도 작동합니다.
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에 비해 기능이 더 제한되는 경우가 많습니다. 예를 들어, Langchain의 Python 버전에는 18개의 문서 변환기 통합이 있는 반면 JavaScript 버전에는 5개가 있습니다.
기본 LLM API
이제 이 작품은 더욱 미래지향적입니다. Google Chrome은 최근 로컬에서 실행되는 Gemini Nano 모델에 대한 액세스를 노출하는 Chrome Dev 및 Chrome Canary 채널에 실험적인 API 세트를 출시했습니다.
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.
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.
