AIパーソナル・ラーニング
と実践的なガイダンス
サイバーナイフ用ドローイングミラー

RAGアプリケーションのためのパーソナライズされたゲーム推薦の迅速な実装:DeepSeekとOllamaのハンズオンガイド

パーソナライズされたおすすめゲームを提供するアプリを作りたいですか?このチュートリアルでは、RAG(Retrieval Augmented Generation)テクニックの使用方法をステップバイステップで説明します。 ディープシーク 歌で応える オーラマ モデルを使用して、カスタマイズされたゲーム推奨システムを作成します。

Epic Games Storeのデータセットを使用します。 games.csv ファイルをデータソースとして使用します。このチュートリアルで選択するテクノロジー・スタックは以下の通りです:

  • 大規模言語モデル(LLM):Ollamaを使用する。 deepseek-r1:1.5b モデル
  • 埋め込みモデル:Weaviateの text2vec_openai コンポーネントをデフォルトの text-embedding-3-small モデル


 

ステップ1: 依存ライブラリのインストールとAPIキーの設定

まず、以下のPythonライブラリをインストールする必要がある。 ラグ アプリケーションに必要な

!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 では、Terminal で以下のコマンドを使用して DeepSeek モデルを実行できます:

ollama run deepseek-r1:1.5b

次のステップに進む前に、モデルが正常に実行されることを確認する。

 

ステップ3:Weaviateコレクションを作成し、入力する

Weaviateコレクションは、ゲームデータの保存と取得に使用されます。以下の手順に従って、Weaviateコレクションを作成し、データを入力してください:

  • games.csvファイルのダウンロード: Kaggleからgames.csvファイルをダウンロード(カグル) をローカル・ディレクトリにコピーする。
  • Weaviate Dockerコンテナの起動:以下の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"
...
  • Games」コレクションの作成:以下の Python コードを実行し、「Games」という 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:埋め込み検索の実行

これで、「Games」コレクションにデータが入力されました。ユーザーのクエリに関連するゲームを取得するために、埋め込み検索を試すことができます。次のコードは、"I play the vilain "に関連するゲームを検索し、最も関連性の高い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パラメータはモデルの生成タスクを定義し、ユーザーのクエリと検索されたゲーム情報に基づいて答えを生成するようモデルに指示し、答えにゲームプラットフォームに関する情報が含まれていることを明示的に要求します。を含むことを明示的に要求します。

recommend_game関数を呼び出してユーザークエリを渡すことで、ゲーム推薦アプリケーションをテストできます。例えば、"魔法の生き物をロールプレイできるゲームは?"というクエリです。

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.

推薦結果を生成するときにモデルが何を考えているかを見たい場合は、response['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 テクニックを使用して、パーソナライズされたレコメンデーションシステムを構築する方法の基本を学びました。ゲームデータの追加、レコメンデーションアルゴリズムの最適化、より良いゲームレコメンデーションサービスを実現するためのユーザーインターフェイスの開発など、ニーズに応じてアプリケーションを拡張・改善することができます。

無断転載を禁じます:チーフAIシェアリングサークル " RAGアプリケーションのためのパーソナライズされたゲーム推薦の迅速な実装:DeepSeekとOllamaのハンズオンガイド
ja日本語