파란하늘의 지식창고
article thumbnail
반응형

이전 글에서 ollama로 llama 3를 로컬에서 실행해서 사용해 보았었다.

ollama 프롬프트에 몇 가지 질문을 던져보면 원하는 답변을 얻을 경우도 있지만 말도 안 되는 엉터리 답변도 그럴싸하게 진실인 것처럼 답변을 한다.

이런 현상을 AI 할루시네이션(Hallucination : 환각)이라고 하는데 다양한 원인들로 인해 발생하고 이를 줄이기 위해 다양한 해결 방법을 사용해야 한다.

LLM에 학습되지 않은 지식을 주입하는 방법이 몇 가지 있다.

  • Fine-Tuning : 현재 사용하는 model에 새로운 지식에 대한 dataset을 추가 학습
  • Retrieval-Augmented Generation (RAG) : 응답을 생성하기 전 학습 datasource 외부의 신뢰할 수 있는 지식 베이스를 참조하도록 하는 프로세스

Find-Tuning은 학습을 통해 다시 좀 더 학습된 model을 만드는 방식이고 RAG는 현재 학습된 model을 기준으로 외부 데이터를 추가하여 응답 보정을 하는 방식이다.

이런 구성을 하기 위해 가장 많이 쓰이는 것이 LangChain이다.
LangChain은 LLM을 기반으로 하는 application을 개발하기 위한 framework이다.

https://www.langchain.com/

python과 javascript에서 사용이 가능하고 여러 LLM을 결합하여 사용하거나 입/출력 및 RAG를 구성하는 등 다양한 기능을 제공한다.

LangChain과 RAG 사용해 보기

이렇게 사용하는 방식에 대해서 안내된 유튜브 영상을 따라 해 보았다.

Llama 3 RAG: How to Create AI App using Ollama?

예제 소스는 다음과 같다.

https://mer.vin/2024/04/llama-3-rag-using-ollama/

python으로 사용해야 하므로 우선 관련 package를 install 한다.

pip install ollama langchain beautifulsoup4 chromadb gradio
pip install langchain-community

설치 시 chroma 관련 오류가 다음처럼 발생한다면

Building wheels for collected packages: chroma-hnswlib
  Building wheel for chroma-hnswlib (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Building wheel for chroma-hnswlib (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [5 lines of output]
      running bdist_wheel
      running build
      running build_ext
      building 'hnswlib' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for chroma-hnswlib
Failed to build chroma-hnswlib
ERROR: Could not build wheels for chroma-hnswlib, which is required to install pyproject.toml-based projects

Microsoft C++ Build Tools를 다운로드하고 C++ build tools (아마 선택 메뉴 중 가장 맨 위 좌측에 위치)를 선택하여 설치해야 한다.

https://visualstudio.microsoft.com/ko/visual-cpp-build-tools/

(내 경우 pip 가 아닌 poetry 로 프로젝트를 만들어보았는데 이 경우 위와 같은 경고가 보이지 않았었다.)

해당 영상에서는 예제가 2가지가 있는데 하나는 특정 주소의 데이터를 가져오면서 질문을 하는 예제였고 다른 하나는 주소와 질문을 입력하면 응답을 반환하는 예제였다.

첫 번째 예제의 경우 로컬의 llm.html 파일의 데이터 중 특정 class에 위치한 데이터를 학습하는 식이었는데 해당 페이지의 소스가 안 보여서 학습이 되지 않았고, 외부 링크로 해보면 오류가 발생하였다.

그래서 어쩔 수 없이 두 번째 예제만 테스트해 보았다.

먼저 해당 예제에서 사용하려는 model을 pull로 가져온다.
(이전에 이미 llama3 는 pull 한 상태이기 때문에 nomic-embed-text 만 pull 해주었다.)

ollama pull nomic-embed-text

이제 python 파일을 만들고 해당 예제를 추가한 후 실행해 본다.

import gradio as gr
import bs4
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import OllamaEmbeddings
import ollama

# Function to load, split, and retrieve documents
def load_and_retrieve_docs(url):
    loader = WebBaseLoader(
        web_paths=(url,),
        bs_kwargs=dict() 
    )
    docs = loader.load()
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    splits = text_splitter.split_documents(docs)
    embeddings = OllamaEmbeddings(model="nomic-embed-text")
    vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)
    return vectorstore.as_retriever()

# Function to format documents
def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

# Function that defines the RAG chain
def rag_chain(url, question):
    retriever = load_and_retrieve_docs(url)
    retrieved_docs = retriever.invoke(question)
    formatted_context = format_docs(retrieved_docs)
    formatted_prompt = f"Question: {question}\n\nContext: {formatted_context}"
    response = ollama.chat(model='llama3', messages=[{'role': 'user', 'content': formatted_prompt}])
    return response['message']['content']

# Gradio interface
iface = gr.Interface(
    fn=rag_chain,
    inputs=["text", "text"],
    outputs="text",
    title="RAG Chain Question Answering",
    description="Enter a URL and a query to get answers from the RAG chain."
)

# Launch the app
iface.launch()

두 번째 예제에서 사용한 gradio는 LLM 사용을 편하게 도와주는 app 라이브러리이고 간단하게 웹페이지를 만들어 사용할 수 있다고 한다.
https://www.gradio.app/

예제를 보면 전달받은 요청 주소를 nomic-embed-text model을 사용하여 vector store에 처리한 후 llama3 model을 사용하여 답변을 하는 것을 알 수 있다.

실행된 로컬 주소가 로그에 보인다.

WARNING:root:USER_AGENT environment variable not set, consider setting it to identify your requests.
Running on local URL:  http://127.0.0.1:7860

해당 주소로 접근하면 다음과 같은 화면이 나타난다.

예를 들어 sprig boot 문서를 주소에 입력하고 현재 spring boot 버전을 물어보면 다음과 같이 답변해 준다.

spring boot 문서가 예전처럼 single 페이지 문서가 아니어서 전체 내용 학습이 아닌 첫 페이지 내용만 학습한 경우여서 버전 정도만 답변이 가능했다.
(관련하여 single page html에 대한 issue가 제기되어 있는 상태이다 : https://github.com/spring-projects/spring-boot/issues/40894)

참고로 ollama3 run llama3 로 실행한 프롬프트에서 동일한 질문을 하면 2022년 11월까지 학습한 내용을 기준으로 답변하기 때문에 다음과 같이 답변하였었다.

C:\>ollama run llama3
>>> 현재 spring boot 버전은?
😄

According to the official Spring Boot website, the current stable version of Spring Boot is:

**Spring Boot 2.4.5**

Released on March 9, 2022.

You can check the latest versions and changelogs at [https://spring.io/projects/spring-boot](https://spring.io/projects/spring-boot).

Keep in mind that newer versions may be available as part of a release candidate or milestone build. Always check the official Spring Boot website for the latest
information! 💡

 

아직 학습하지 않은 내용에 대해 질문하면 모른다고 답변하지 않고 사실이 아닌 걸 사실인 것처럼 답변을 한다.

llama3 프롬프트에 현재 나오지도 않은 spring boot 버전의 새로운 기능에 대해 직접 질문해 보면 마치 진짜 있는 것 마냥 답변을 한다.

>>> spring boot 4.3.2의 새로운 기능을 알려줘
🌷 Spring Boot 4.3.2 has introduced several new features and improvements. Here are some of the notable ones:

1. **Improved WebFlux**: The WebFlux framework, which provides a reactive web framework for building web applications, has been improved with better error handling,
support for multipart requests, and more.
2. **Support for Java 17**: Spring Boot now supports Java 17, which brings new features like pattern matching for instanceof, record types, and more.
3. **Improved Micrometer Instrumentation**: The Micrometer library, which provides metrics and monitoring capabilities, has been improved with better instrumentation for
HTTP requests, JDBC queries, and more.
4. **Better Support for AWS Lambda**: Spring Boot now provides better support for building serverless applications using AWS Lambda, including automatic handling of
asynchronous invocations.
5. **Improved Support for Azure Functions**: Similarly, Spring Boot has improved support for building serverless applications using Azure Functions, including automatic
handling of asynchronous invocations.
6. **Enhanced Support for OpenFeign**: The OpenFeign library, which provides a client-side HTTP API for making remote procedure calls (RPCs), has been enhanced with
better error handling and more features.
7. **Improved Support for Reactive Streams**: Spring Boot now provides better support for building reactive applications using the Reactive Streams API, including
improved error handling and more features.
8. **New Features in Actuator**: The Actuator library, which provides a set of tools for monitoring and managing your application, has been updated with new features
like HTTP request metrics and more.
9. **Improved Support for Kafka**: Spring Boot now provides better support for building applications that integrate with Apache Kafka, including improved error handling
and more features.

These are just a few examples of the new features and improvements in Spring Boot 4.3.2. For a complete list, I recommend checking out the official documentation:
https://spring.io/blog/2022/03/15/spring-boot-4-3-2-is-released 🎉

 


 

LangChain과 RAG, gradio를 사용하여 손쉽게 추가적인 데이터를 학습시키고 답변을 받을 수 있다는 것을 알게 되었다.
또한 llm model이 올바르지 않은 응답을 그럴싸하게 만들어내는 것도 확인하였다.
계속 사용해 보고 익숙해져서 이러한 AI 할루시네이션 문제를 해결하고 편하게 사용할 수 있었으면 좋겠다.

반응형
profile

파란하늘의 지식창고

@Bluesky_

도움이 되었다면 광고를 클릭해주세요