본문 바로가기

인공지능

로컬 llm 구현

1. ollama설치

https://ollama.com/

 

Ollama

Get up and running with large language models.

ollama.com

위 사이트에서 ollama 다운로드 및 설치

2. ollama에서 open llm 설치

cmd 창에서 

ollama pull [llm 이름]

명령어 실행

저는 이번에 새로나온 gemma2를 사용할 예정이기 때문에

ollama run gemma2:9b

로 설치 진행하였습니다.

3. 메모리 기능 추가

from langchain_community.llms import Ollama
from langchain.memory import ConversationSummaryBufferMemory
from langchain.schema.runnable import RunnablePassthrough
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder

llm = Ollama(model="gemma2")

memory = ConversationSummaryBufferMemory(
    llm=llm,
    max_token_limit=80,
    memory_key="chat_history",
    return_messages=True,
)

def load_memory(input):
    return memory.load_memory_variables({})["chat_history"]

prompt = ChatPromptTemplate.from_messages([
    ("system", f"역활은 한글을 영어로 바꾸는 번역기"),
    MessagesPlaceholder(variable_name="chat_history"),
    ("human", "{question}"),
])

chain = RunnablePassthrough.assign(chat_history=load_memory) | prompt | llm

def invoke_chain(question):
    result = chain.invoke({"question": question})
    memory.save_context(
        {"input": question},
        {"output": result},
    )
    print(result)

while True :
    print("명령을 입력하세요")
    userInput = input()
    invoke_chain(userInput)

ChatPromptTemplete에는  human, system, ai와 같은 특정 역활이 사전 정의 되어있습니다.

System에 위와 같이 등록을 할 경우 번역기로 써 작동이 됩니다.

4. 테스트

위 소스 코드를 동작 시 

위와 같이 동작하는 것을 볼 수 있습니다.