LangChain은 LLM(Large Language Model) 모델을 통해 다양한 작업을 수행할 수 있게 하는 라이브러리입니다. 주로 자연어 처리(NLP)와 인공지능(AI) 애플리케이션을 구축하는 데 사용됩니다. LangChain.js는 이러한 LangChain의 기능을 JavaScript 환경에서 사용할 수 있도록 하는 라이브러리입니다. 핵심 기능은 RAG ( Retrieval Augmented Generation) 이라고 할 수 있으며, 추후 자세히 이야기 해보겠습니다.
npm install langchain @langchain/openai
// @langchain/core
@langchain/core 는 langchain 의 dependency 이며, 동시에 @langchain/openai 의 dependency 입니다. 따라서 별도 설치가 필요하지 않으며, package.json의 "dependencies" 에도 명시되지 않습니다. npm ls @langchain/core로 디펜던시 구조를 들여다 보면, deduped 처리된 것을 볼 수 있습니다.( deduped는 특히 의존성 트리에서 중복된 패키지를 제거했음을 나타냅니다)
// langchain doc 에 모든 properties 있음
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import {
StringOutputParser,
CommaSeparatedListOutputParser,
} from "@langchain/core/output_parsers";
import { StructuredOutputParser } from "langchain/output_parsers";
import { z } from "zod";
import * as dotenv from "dotenv";
dotenv.config();
// 모델 만들기
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo",
temperature: 0.7,
});
async function callStringOutputParser() {
// prompt template 만들기
const prompt = ChatPromptTemplate.fromMessages([
["system", "Generate a joke on a word provided by the user."],
["human", "{input}"],
]);
// parser 만들기
const parser = new StringOutputParser(); // 줄바꿈기호(\n)등 사라짐
// chain 만들기
const chain = prompt.pipe(model).pipe(parser);
// chain 호출하기
return await chain.invoke({
input: "dog",
});
}
async function callListOutputParser() {
const prompt = ChatPromptTemplate.fromTemplate(`
Provide 5 synonyms, seperated by commas, for the following word {word}
`);
const outputParser = new CommaSeparatedListOutputParser();
const chain = prompt.pipe(model).pipe(outputParser); // .pipe(outputParser)없으면 콤머로 구분된 하나의 스트링으로 표기됨
return await chain.invoke({
word: "happy",
});
}
async function callStructuredParser() {
const prompt = ChatPromptTemplate.fromTemplate(`
Extract information from the following phrase.
Formatting Instruction: {format_instructions}
Phrase: {phrase}
`);
// new 안붙임, StructuredOutputParser.fromNamesAndDescriptions is not a constructor
const structedOutputParser = StructuredOutputParser.fromNamesAndDescriptions({
name: "the name of the person",
age: "the age of the person",
});
const chain = prompt.pipe(model).pipe(structedOutputParser);
return await chain.invoke({
phrase: "John is 20 years old who lives in this town.",
format_instructions: structedOutputParser.getFormatInstructions(),
});
}
async function callZodOutputParser(){
const prompt = ChatPromptTemplate.fromTemplate(`
Extract information from the following phrase.
Formatting Instruction: {format_instructions}
Phrase: {phrase}
`)
const structedOutputParser = StructuredOutputParser.fromZodSchema(
z.object({
recipe: z.string().describe("name of recipe"),
ingredients: z.array(z.string()).describe("ingredients"),
})
);
const chain = prompt.pipe(model).pipe(structedOutputParser);
return await chain.invoke({
phrase: " The incredients for a Spaghetti Bolognese recipe are tomatoes, minced beef, garlic, wine and herbs.",
format_instructions: structedOutputParser.getFormatInstructions(),
})
}
// const response = await callStringOutputParser(); //Why did the dog sit in the shade? Because he didn't want to be a hot dog!
// const response = await callListOutputParser(); //[ 'joyful', 'content', 'delighted', 'pleased', 'elated' ]
// const response = await callStructuredParser(); // { name: 'John', age: '20' } // object
const response = await callZodOutputParser();
// {
// recipe: 'Spaghetti Bolognese',
// ingredients: [ 'tomatoes', 'minced beef', 'garlic', 'wine', 'herbs' ]
// }
// object
console.log(response);
console.log(typeof response); // object -자바스크립트 오브젝트
Models, Datasets, Spaces - Hugging Face (0) | 2024.07.03 |
---|---|
.env - @ai-sdk/openai (1) | 2024.06.19 |
.env 과 인스턴스(model) 만들기 - langchain.js (0) | 2024.06.13 |
faiss-node (0) | 2024.06.13 |
Ai (0) | 2024.06.08 |