๐ฆ๐ LangSmith ์ฐ๊ฒฐ
LangSmith ์ฐ๊ฒฐ์ ์ํด .env ํ์ผ์ LangSmith API Key๋ฅผ ์์ฑํ์.
์ด ์์
๋ง ํด์ฃผ๋ฉด ์๋์ผ๋ก ์ธํ
ํ ํ๋ก์ ํธ๋ช
์ผ๋ก LangSmith์์ Application ๋ชจ๋ํฐ๋ง์ด ๊ฐ๋ฅํ๋ค.
# .env
LANGCHAIN_API_KEY="Your API Key"
LANGCHAIN_PROJECT="Project Name"
# app.py
from dotenv import load_dotenv
load_dotenv()
๐ค LLM ๋ชจ๋ธ ์ธํ
LangChain์ ChatGPT, Ollama, Gemini, Huggingface ๋ฑ ๋ค์ํ LLM์ ์ด์ฉํ ์ ์๋ค.
์ํฉ์ ๋ฐ๋ผ ๋ณธ์ธ์ด ์ฌ์ฉํ๊ณ ์ ํ๋ ๋ชจ๋ธ์ ๋ก๋ํ๊ธฐ๋ง ํ๋ฉด ๋๋ค.
์๋์ Document์์ LangChain์ด ์ด๋ค LLM์ ์ง์ํ๋์ง ํ์ธํ ์ ์๋ค.
from langchain_google_genai import ChatGoogleGenerativeAI
# Google์ gemini-pro ๋ชจ๋ธ ์ฌ์ฉ
model = ChatGoogleGenerativeAI(model="gemini-pro",
convert_system_message_to_human=True,
)
๐ข OutputParser
LLM์ ์ฌ์ฉ์์ ์ง๋ฌธ์ ๋ํด AIMessageํํ์ ๋ฐ์ดํฐ๋ฅผ ๋ฐํํ๋ค.
์ด ๋ฐ์ดํฐ์๋ ๋ค์ํ ๋ฉํ๋ฐ์ดํฐ๋ ํจ๊ป ํฌํจ๋๊ธฐ ๋๋ฌธ์ OutputParser๋ฅผ ํตํด ์ง๋ฌธ์ ๋ํ ๋๋ต๋ง ํ์ฑํ ์ ์๋ค.
# app.py
from langchain_core.output_parsers import StrOutputParser
parser = StrOutputParser()
๐ Prompt Template
ํน์ ๊ธฐ์ ์ด ์ด๋ค ์ฌ์ ์ผ๋ก ๋์ ๋ฒ๊ณ ์๋์ง ๋ถ์ํด์ฃผ๋ LLM Application์ ๋ง๋ ๋ค๊ณ ๊ฐ์ ํด๋ณด์. ์ฌ์ฉ์๋ ~~ ๊ธฐ์ ์ด ์ด๋ค ์ฌ์ ์ผ๋ก ๋์ ๋ฒ๋์ง ๋ถ์ํด์ ์๋ ค์ค ๋ผ๋ ํน์ ์์์ ์ง๋ฌธ์ ๊ณ์ํด์ ๋ฐ๋ณตํด์ผ ํ ๊ฒ์ด๋ค.
Prompt Template์ ์ด์ฉํ๋ฉด ์ฌ์ฉ์๋ก๋ถํฐ ์ต์ํ์ Input ์ ๋ณด๋ง์ ๋ฐ์ Template์ผ๋ก ๋ง๋ค์ด LLM ๋ชจ๋ธ์ ์์ฑ๋ ์ง๋ฌธ์ ์ ๋ฌํ๋ ๊ฒ์ด ๊ฐ๋ฅํด์ง๋ค.
์๋์ template์ ์ด์ฉํ๋ฉด ์ฌ์ฉ์๋ company ๋ณ์์ ํด๋นํ๋ ๋ถ๋ถ๋ง ์ ๋ ฅํด๋ ์์ฑ๋ ์ง๋ฌธ์ LLM์ ์ ๋ฌํ ์ ์๋ค.
# app.py
from langchain_core.prompts import ChatPromptTemplate
system_template = "{company}๊ฐ ์ด๋ค ์ฌ์
์ผ๋ก ๋์ ๋ฒ๋์ง ์๋ ค์ค"
prompt_template = ChatPromptTemplate.from_messages(
[("system", system_template), ("user", "{company}")]
)
๐ LCEL๋ฌธ๋ฒ์ ์ด์ฉํ Chain์์ฑ
์์ ์ค๋นํ LLM ๋ชจ๋ธ, Prompt Template, Output Parser ์ธ๊ฐ์ง๋ฅผ LCEL ๋ฌธ๋ฒ์ ํตํด Chain์ ์์ฑํ๋ค.
chain = prompt_template | model | parser
๐ฆ๐ LangServe๋ฅผ ์ด์ฉํ ์ดํ๋ฆฌ์ผ์ด์ ๋ฐฐํฌ
langserve๋ฅผ ์ด์ฉํด LLM Application์ localhost์ ๋ฐฐํฌํด๋ณด์.
langserve ํจํค์ง์์ ์ ๊ณตํ๋ add_routes ๋ฉ์๋๋ฅผ ์ด์ฉํด Application์ ๋ํ ์ ๋ณด, LLM Chain, ๊ฒฝ๋ก ์ธ๊ฐ์ง๋ฅผ ์ง์ ํด์ค๋ค.
pip install "langserve[all]"
from langserve import add_routes
...
# define app
app = FastAPI(
title="LangChain Server",
version="1.0",
description="A simple API server using LangChain's Runnable interfaces",
)
# adding chain route
add_routes(
app,
chain,
path="/chain"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="localhost", port=8000)
์๋์ ๋ช ๋ น์ด๋ก application์ ์คํํ ์ ์๋ค.
python app.py
๐ข Playground
http://localhost:8000/chain/playground/ ๊ฒฝ๋ก๋ก ์ด๋ํ๋ฉด Playground๋ฅผ ํตํด LLM Application ํ ์คํธ๊ฐ ๊ฐ๋ฅํ๋ค.
LangSmith์์๋ ๋ชจ๋ํฐ๋ง์ด ์ฐ๋๋๋๊ฒ์ ํ์ธํ ์ ์๋ค.
Ref: https://python.langchain.com/v0.2/docs/tutorials/llm_chain/
'LangChain' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LangChain] Reranker (0) | 2024.08.29 |
---|---|
[LangChain] RAG VectorStore & Retrievers (4) | 2024.08.29 |
[LangChain] Chatbot Message History (1) | 2024.08.29 |
[LangChain] LangChain ์์ํ๊ธฐ (1) | 2024.08.29 |