AI个人学习
和实操指南
讯飞绘镜

快速实现个性化游戏推荐 RAG 应用:DeepSeek & Ollama 实践指南

想要构建一个能够提供个性化游戏推荐的应用吗?本教程将一步步指导你使用检索增强生成(RAG)技术,结合 DeepSeekOllama 模型,打造一个定制化的游戏推荐系统。

我们将使用 Epic Games 商店数据集中的 games.csv 文件作为数据源。本教程的技术栈选择如下:

  • 大型语言模型 (LLM): 我们将使用 Ollama 运行的 deepseek-r1:1.5b 模型。
  • 嵌入模型: 我们将使用 Weaviate 的 text2vec_openai 组件,并采用默认的 text-embedding-3-small 模型。

blank


 

步骤 1:安装依赖库并配置 API 密钥

首先,你需要安装以下 Python 库,这些库是构建和运行 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 官方文档 (Ollama Docs) 完成安装和模型拉取。

以 macOS 系统为例,你可以使用以下命令在终端中运行 DeepSeek 模型:

ollama run deepseek-r1:1.5b

确保模型成功运行后,再进行下一步。

 

步骤 3:创建并填充 Weaviate 集合

Weaviate 集合用于存储和检索游戏数据。按照以下步骤创建并填充你的 Weaviate 集合:

  • 下载 games.csv 文件: 从 Kaggle 下载 games.csv 文件 (Kaggle) 到你的本地目录。
  • 启动 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 函数并传入用户查询来测试你的游戏推荐应用。例如,查询 "What are some games that I get to role play a magical creature" (有哪些游戏可以扮演魔法生物)。

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 实践指南

首席AI分享圈

首席AI分享圈专注于人工智能学习,提供全面的AI学习内容、AI工具和实操指导。我们的目标是通过高质量的内容和实践经验分享,帮助用户掌握AI技术,一起挖掘AI的无限潜能。无论您是AI初学者还是资深专家,这里都是您获取知识、提升技能、实现创新的理想之地。

联系我们
zh_CN简体中文