1.HuggingFace API Key 발급
로그인후 우측 상단 캐릭터를 누르고 Settings에 들어간다.
좌측 메뉴에서 Access Tokens 를 찾아 누른다.
Create new Token을 누르고 Read 모드로 토큰이름을 입력후 발급받는다.
2.LangChain에서 HuggingFace 모델 사용(Inference API)
langchain_huggingface 모듈을 통해 HuggingFaceEndpoint를 불러와서
발급받은 API Token으로 모델을 불러올수있다.
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_huggingface import HuggingFaceEndpoint
import os
repo_id = "microsoft/Phi-3-mini-4k-instruct"
llm = HuggingFaceEndpoint(
repo_id=repo_id,
max_new_tokens=256,
temperature=0.1,
huggingfacehub_api_token=os.environ["HUGGINGFACEHUB_API_TOKEN"],
)
template = """
<|system|>당신은 모든 대답을 한국어로 하고 친절하게 대답합니다.<|end|>
<|user|>{Question}<|end|>
<|assistant|>
"""
prompt = PromptTemplate.from_template(template=template)
chain = prompt | llm | StrOutputParser()
while True:
Question = input("질문: ")
result = chain.invoke({"Question": Question})
print(result)
질문: 한국이 뭐야
한국은 아르헨티나 및 베트남과 같은 아시아 국가입니다. 아시아 중 한 반도 위에 위치하고 있으며, 한국은 체코 반도체 끼리 결혼하고 있습니다. 한국의 문화, 음식, 예술, 역사, 그리고 특히 삼각탄자류를 세계적으로 유명하게 유지되고 있습니다.
Inference API방식은 Billing란에서 남은 사용량을 조회할수있다.
보면 무료 플랜에서는 하루 1000번의 요청을 할수있다고 한다.
You can do up to 1,000 requests on the Serverless Inference API per day.
Subscribe to PRO to increase your daily request limit to 20,000.
무료 플랜: 하루에 최대 1,000번의 요청을 할 수 있습니다.
PRO 플랜: PRO 플랜에 가입하면 하루에 최대 20,000번의 요청을 할 수 있습니다.
3.로컬에서 HuggingFace 모델 다운받아서 사용
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_huggingface import HuggingFacePipeline
import os
os.environ["TRANSFORMERS_CACHE"] = "./cache/"
os.environ["HF_HOME"] = "./cache/"
llm = HuggingFacePipeline.from_model_id(
model_id="microsoft/Phi-3-mini-4k-instruct",
task="text-generation",
pipeline_kwargs={
"max_new_tokens": 256,
"top_k": 50,
"temperature": 0.1,
},
)
template = """
<|system|>당신은 모든 대답을 한국어로 하고 친절하게 대답합니다.<|end|>
<|user|>{Question}<|end|>
<|assistant|>
"""
prompt = PromptTemplate.from_template(template=template)
chain = prompt | llm | StrOutputParser()
while True:
Question = input("질문: ")
result = chain.invoke({"Question": Question})
print(result)
반응형
'AI' 카테고리의 다른 글
[LangChain] RAG(Retrieval-Augmented Generation) (0) | 2025.01.15 |
---|---|
[LangChain] InMemoryCache (0) | 2025.01.13 |
[LangChain] 출력 파서(Output Parsers) (0) | 2025.01.13 |