본문 바로가기
데이터&AI/langchain

[langchain + ollama] langchain으로 llama3 호출하기!!(feat. python, 멀티에이전트)

by 일등박사 2024. 6. 2.
728x90

 

2024.05.29 - [데이터&AI/LLM] - llama3 의 모델을 api로 호출하기!! (feat. ollama, python, embedding)

 

llama3 의 모델을 api로 호출하기!! (feat. ollama, python, embedding)

지난 포스팅에서는!! ollama로  올라간 llama를shell 환경에서 진행해보았는데요!! 이번에는 API를 호출하는 방법으로 해당 모델을 사용해보겠습니다!! 1. ollama모델 구동 - 기존과 동일하게, 서버에

drfirst.tistory.com

 

지난 포스팅에서는 ollama의 llama3를

python의 api request를 활용하여 사용했었습니다!!

이번에는 python의 langchain 패키지를 활용하여 llama3를 활용해봅시가!!

 


1. ollama모델 구동

 - 기존과 동일하게, 서버에서 ollama를 우선 구동시킵니다!!

 

OLLAMA_MODELS={모델의 위치} ollama serve

 

 

2. python langchain으로 API 호출

from langchain_community.llms import Ollama

llama3 = Ollama(model="llama3")

llama3.invoke("Tell me some beautiful story")

위와 같이 아주 간단합니다!!!

 

 


+ multi agent의 langchain활용

langchain의 기능을 활용하여

GPT4, llama3, llama2를 혼합한 모델을 사용할 수 있습니다!!

 

> 우선 각 모델을 호출합니다

from langchain_community.llms import Ollama
from langchain.chat_models import ChatOpenAI
from langchain.output_parsers.json import SimpleJsonOutputParser
from langchain_core.output_parsers import StrOutputParser
from langchain.prompts import ChatPromptTemplate

llama3 = Ollama(model="llama3")
chatgpt4 = ChatOpenAI(openai_api_key  = openai_key,model='gpt-4o')
llama2 = Ollama(model="llama2-uncensored")

 

필요한 모델을 상활별로 활용하며 답을 구해줍니다!

 

## 미션1 : GPT4로 농담구하기

my_question = """
tell me some joke about {input}
"""
str_parser = StrOutputParser()
prompt_revenuesentence = ChatPromptTemplate.from_template(my_question)
chain_revenuesentence  = prompt_revenuesentence | chatgpt4 | str_parser 
gpt4_res = chain_revenuesentence.invoke({"input": 'penguin'})
print(gpt4_res)

###미션2 : LLAMA3로 농담 중 하나 선정하기
my_question2 = """
select only one the best joke {joke_res}
"""
str_parser = StrOutputParser()
prompt_revenuesentence = ChatPromptTemplate.from_template(my_question2)
chain_revenuesentence  = prompt_revenuesentence | llama3 | str_parser 

llama3_res = chain_revenuesentence.invoke({"joke_res": gpt4_res})
print(llama3_res)

###미션3 : LLAMA2로 농담이유 소개받기
my_question3 = """
{joke_res}
why is this a joke?? tell me in detail

"""
str_parser = StrOutputParser()
prompt_revenuesentence = ChatPromptTemplate.from_template(my_question3)
chain_revenuesentence  = prompt_revenuesentence | chatgpt4 | str_parser 
llama2_res = chain_revenuesentence.invoke({"joke_res": llama3_res})
print(llama2_res)

 

결과를 보면!!

 

1. "펭귄" 관련 농담을 만들어줘! (gpt-4o)

 

 

2. 농담중에 베스트를 뽑아줘 (llama3)

 

3 농담을 해석해줘 (llama2)

 

 

 

이제 필요한 상황별로 알맞은 llm model 을 선정해서 동작시킬수 있겠지요!?

 

ㅁ 참고 : https://python.langchain.com/v0.1/docs/integrations/llms/ollama/

 

Ollama | 🦜️🔗 LangChain

Ollama allows you to run open-source large language models, such as Llama 2, locally.

python.langchain.com

 

 

728x90

댓글