RAG 애플리케이션을 위한 개인화된 게임 추천의 신속한 구현: DeepSeek 및 Ollama 실습 가이드
개인화된 게임 추천을 제공하는 앱을 만들고 싶으신가요? 이 튜토리얼에서는 검색 증강 생성(RAG) 기법을 검색 증강 생성 기법과 결합하여 DeepSeek 노래로 응답 Ollama 모델을 사용하여 맞춤형 게임 추천 시스템을 만들 수 있습니다.
에픽게임즈 스토어 데이터 세트는 다음과 같이 사용할 예정입니다. games.csv
파일을 데이터 소스로 사용합니다. 이 튜토리얼에서 선택할 수 있는 기술 스택은 다음과 같습니다:
- 대규모 언어 모델(LLM): Ollama를 사용하여 다음과 같이 실행합니다.
deepseek-r1:1.5b
모델. - 임베딩 모델: Weaviate의
text2vec_openai
컴포넌트를 기본text-embedding-3-small
모델.

1단계: 종속 라이브러리 설치 및 API 키 구성하기
먼저, 다음 파이썬 라이브러리를 설치해야 합니다. RAG 애플리케이션에 필요합니다.
!pip install weaviate-client pandas tqdm ollama
다음으로 OpenAI의 임베딩 모델을 사용하려면 OpenAI API 키를 설정해야 합니다. 아직 설정하지 않았다면 다음 단계를 따르세요:
from getpass import getpass
import os
if "OPENAI_APIKEY" not in os.environ:
os.environ["OPENAI_APIKEY"] = getpass("Enter your OpenAI API Key")
이 코드는 환경 변수에 OPENAI_APIKEY가 이미 존재하는지 확인하고, 존재하지 않으면 OpenAI API 키를 입력하고 환경 변수로 설정하라는 메시지를 표시합니다.
2단계: DeepSeek 모델 실행
이 튜토리얼에서는 Ollama를 사용해 로컬에서 deepseek-r1:1.5b 모델을 실행합니다. 아직 Ollama를 설치하지 않고 deepseek-r1:1.5b 모델을 가져오지 않은 경우 공식 Ollama 문서를 참조하여 설치 및 모델 가져오기를 완료하세요.
예를 들어 macOS의 경우 터미널에서 다음 명령을 사용하여 DeepSeek 모델을 실행할 수 있습니다:
ollama run deepseek-r1:1.5b
다음 단계로 진행하기 전에 모델이 성공적으로 실행되는지 확인합니다.
3단계: Weaviate 컬렉션 생성 및 채우기
Weaviate 컬렉션은 게임 데이터를 저장하고 검색하는 데 사용됩니다. 아래 단계에 따라 Weaviate 컬렉션을 생성하고 채우세요:
- games.csv 파일 다운로드: Kaggle에서 games.csv 파일 다운로드(Kaggle)를 로컬 디렉토리에 추가합니다.
- Weaviate 도커 컨테이너 시작하기: 다음 docker-compose.yml 파일을 사용하여 Weaviate를 시작하고 generative-ollama 및 text2vec-openai 모듈이 활성화되어 있는지 확인합니다. 다음을 docker-compose.yml 파일로 저장하고 터미널에서 docker compose up 명령을 사용하여 Weaviate를 시작합니다.
---
services:
weaviate_anon:
command:
- --host
- 0.0.0.0
- --port
- '8080'
- --scheme
- http
image: cr.weaviate.io/semitechnologies/weaviate:1.28.4
ports:
- 8080:8080
- 50051:50051
restart: on-failure:0
environment:
QUERY_DEFAULTS_LIMIT: 25
AUTHENTICATION_ANONYMOUS_ACCESS_ENABLED: 'true'
PERSISTENCE_DATA_PATH: '/var/lib/weaviate'
ENABLE_API_BASED_MODULES: 'true'
BACKUP_FILESYSTEM_PATH: '/var/lib/weaviate/backups'
CLUSTER_HOSTNAME: 'node1'
LOG_LEVEL: 'trace'
ENABLE_MODULES: "text2vec-openai,generative-ollama"
...
- "게임" 컬렉션 만들기: 다음 Python 코드를 실행하여 "게임"이라는 Weaviate 컬렉션을 만듭니다. 이 코드는 게임 이름, 가격, 플랫폼, 출시일, 설명 등 컬렉션의 속성을 정의하고 generative-ollama 및 text2vec-openai 모듈을 구성합니다.
import weaviate
import weaviate.classes.config as wc
from weaviate.util import generate_uuid5
import os
from tqdm import tqdm
import pandas as pd
headers = {"X-OpenAI-Api-Key": os.getenv("OPENAI_APIKEY")}
client = weaviate.connect_to_local(headers=headers)
if client.collections.exists("Games"):
client.collections.delete("Games")
client.collections.create(
name="Games",
properties=[
wc.Property(name="name", data_type=wc.DataType.TEXT),
wc.Property(name="price", data_type=wc.DataType.INT),
wc.Property(name="platforms", data_type=wc.DataType.TEXT_ARRAY),
wc.Property(name="release_date", data_type=wc.DataType.DATE),
wc.Property(name="description", data_type=wc.DataType.TEXT),
],
generative_config=wc.Configure.Generative.ollama(model="deepseek-r1:1.5b",
api_endpoint="http://host.docker.internal:11434"),
vectorizer_config=wc.Configure.Vectorizer.text2vec_openai(),
)
- 게임 데이터 가져오기: 다음 코드를 사용하여 games.csv 파일에서 "Games" 컬렉션으로 데이터를 가져옵니다. 이 코드는 CSV 파일을 읽고 각 데이터 행을 Weaviate 객체로 변환한 다음 컬렉션에 일괄적으로 추가합니다.
games = client.collections.get("Games")
df = pd.read_csv('games.csv')
with games.batch.dynamic() as batch:
for i, game in tqdm(df.iterrows()):
platforms = game["platform"].split(',') if type(game["platform"]) is str else []
game_obj = {
"name": game["name"],
"platforms": platforms,
"price": game["price"],
"release_date": game["release_date"],
"description": game["description"],
}
batch.add_object(
properties=game_obj,
uuid=generate_uuid5(game["id"])
)
if len(games.batch.failed_objects) > 0:
print(f"Failed to import {len(games.batch.failed_objects)} objects")
print(games.batch.failed_objects)
4단계: 임베디드 검색 수행
이제 '게임' 컬렉션이 데이터로 채워졌습니다. 임베디드 검색을 수행하여 사용자의 쿼리와 관련된 게임을 검색할 수 있습니다. 다음 코드는 "나는 악당을 플레이한다"와 관련된 게임을 쿼리하여 가장 관련성이 높은 결과 3개를 반환하는 방법을 보여줍니다.
response = games.query.near_text(query="I play the vilain", limit=3)
for o in response.objects:
print(o.properties)
이 코드는 플랫폼, 설명, 가격, 출시일, 이름 등 쿼리와 관련된 게임의 3가지 속성에 대한 정보를 출력합니다.
5단계: 권장 RAG 애플리케이션 구축
더 스마트한 게임 추천을 구현하려면 RAG 애플리케이션을 만들어야 합니다. 다음 recommend_game 함수가 이를 수행합니다. 이 함수는 사용자 쿼리를 입력으로 받아 가장 관련성이 높은 게임 5개를 검색하고 deepseek-r1:1.5b 모델을 사용하여 개인화된 추천을 생성합니다.
def recommend_game(query: str):
response = games.generate.near_text(
query=query,
limit=5,
grouped_task=f"""You've been provided some relevant games based on the users query.
Provide an answer to the query. Your final answer MUST indicate the platform each game is available on.
User query: {query}""",
grouped_properties=["name", "description", "price", "platforms"],
)
return {'thought':response.generated.split('</think>')[0], 'recommendation': response.generated.split('</think>')[1]}
이 함수는 벡터 검색을 수행할 뿐만 아니라 생성 모델을 사용하여 검색된 게임 정보를 기반으로 추천 텍스트를 생성하는 games.generate.near_text 메서드를 사용합니다. grouped_task 파라미터는 모델의 생성 작업을 정의하여 사용자의 쿼리와 검색된 게임 정보를 기반으로 답변을 생성하도록 모델에 지시하고, 답변에 다음 정보를 포함하도록 명시적으로 요청합니다. 게임 플랫폼에 대한 정보를 포함하도록 명시적으로 요청합니다.
추천 게임 함수를 호출하고 사용자 쿼리를 전달하여 게임 추천 애플리케이션을 테스트할 수 있습니다. 예를 들어, "마법 생물을 역할로 플레이할 수 있는 게임은 무엇인가요?"라는 쿼리를 전달할 수 있습니다.
response = recommend_game("What are some games that I get to role play a magical creature")
print(response['recommendation'])
이 코드를 실행하면 모델에서 생성한 게임 추천 결과를 확인할 수 있습니다:
Here are several games that allow you to role-play as a magical creature:
1. **Mages of Mystralia**
- **Platform:** Windows
- Description: A fantasy RPG where you design your own spells in a world of magic, allowing creativity and flexibility.
2. **Geneforge 1 - Mutagen**
- **Platforms:** Windows, Mac
- Description: An open-ended RPG with mutant monsters, multiple skills, treasures, factions, and creation possibilities, offering unparalleled freedom and replayability.
3. **Beasts of Maravilla Island**
- **Platform:** Windows
- Description: A 3D adventure game where you role as a wildlife photographer exploring magical ecosystems, focusing on behavior learning for photography.
4. **Paper Beast**
- **Platforms:** Windows (PC)
- Description: An adventure game about disrupting wildlife balance with a focus on exotic creatures and mystery-solving.
5. **Black Book**
- **Platform:** Windows
- Description: A dark RPG based on Slavic myths, played as a young sorceress in a world of mythological creatures through card-based battles.
Each game offers unique experiences suitable for role-playing as a magical creature.
추천 결과를 생성할 때 모델이 어떤 생각을 하고 있는지 확인하려면 응답['thought'] 속성을 인쇄하면 됩니다:
print(response['thought'])
이렇게 하면 모델의 사고 과정이 백그라운드에서 출력되어 추천 로직을 더 잘 이해하는 데 도움이 됩니다.
<think>
Okay, so I need to figure out some games that let me role-play as a magical creature. The user provided several options, each with a description and platform. Let me go through them one by one.
First up is "Mages of Mystralia." From the description, it's a fantasy RPG where you design your own spells in a world of magic. That sounds perfect because it allows for a lot of creativity as a magical creature. The platform is Windows, so maybe the user can run it on their PC or any desktop system.
Next is "Geneforge 1 - Mutagen." This seems like an open-ended RPG with mutant monsters and a battle mechanic. It's described as having countless skills, treasures, factions, and creation possibilities. Unmatched freedom and replayability make sense because it allows for various storylines. The platform here is Windows and Mac, so compatible options would be useful.
Then there's "Beasts of Maravilla Island." As the name suggests, it's a 3D adventure game where you take on a wildlife photographer exploring ecosystems. It focuses on behavior learning and photography, which could be exciting for someone looking to role-play in nature. The platform is Windows, so that should be accessible.
"Paper Beast" is another adventure game mentioned. It's about an unknown power disrupting wildlife balance, with players joining exotic creatures to solve mysteries. While it's PC-focused, maybe there are porting options available or different devices that can run it if the user has access to them.
Lastly, "Black Book." This dark RPG is based on Slavic myths and played as a young sorceress. It involves card-based battles in a world with mythological creatures. The platform here is Windows, so maybe older hardware might be a bit limiting unless the user has an updated PC or a dedicated console.
I should make sure each game is listed clearly with their platforms and any necessary details about how they work as magical creatures. Also, it's good to offer a couple of options if some aren't available. Maybe suggest cross-platform games or platforms that can be used for playing.
</think>
축하합니다! DeepSeek와 Ollama를 기반으로 게임 추천 RAG 애플리케이션을 성공적으로 구축했습니다. 이 튜토리얼에서는 대규모 언어 모델 및 벡터 데이터베이스와 결합된 RAG 기술을 사용하여 개인화된 추천 시스템을 구축하는 방법의 기초를 배웠습니다. 더 많은 게임 데이터를 추가하거나 추천 알고리즘을 최적화하거나 사용자 인터페이스를 개발하여 더 나은 게임 추천 서비스를 만드는 등 필요에 따라 애플리케이션을 확장하고 개선할 수 있습니다.
© 저작권 정책
이 글은 저작권이 있으며 무단으로 복제해서는 안 됩니다.
관련 문서
댓글 없음...