极客时间: 用 Word2Vec, LangChain, Gemma 模拟全本地检索增强生成(RAG)

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗?订阅我们的简报,深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同,从行业内部的深度分析和实用指南中受益。不要错过这个机会,成为AI领域的领跑者。点击订阅,与未来同行! 订阅:https://rengongzhineng.io/

最近,Apple的研究人员推出了ReALM,紧随Google的Gemma、Meta的Llama以及微软的其他几个产品之后,完全本地运行大型语言模型(LLM)的应用越来越受到关注。我在《宅乐时光:用Gemma在本地玩LangChain 2》中尝试了本地运行Langchain,唯一缺失的是嵌入部分。为了在本地完整模拟RAG,我在以下代码中添加了word2vec嵌入。

复制代码
import json
import numpy as np
from gensim.models import KeyedVectors
from langchain_community.llms import Ollama 
import logging

# 基础日志配置
logging.basicConfig(level=logging.INFO)

# 使用预训练的Word2Vec模型计算嵌入
def compute_embeddings(text, embedding_model):
    words = [word for word in text.split() if word in embedding_model.key_to_index]
    if words:
        return np.mean([embedding_model[word] for word in words], axis=0)
    else:
        return np.zeros(embedding_model.vector_size)

# 加载预训练的Word2Vec嵌入
try:
    model_path = 'GoogleNews-vectors-negative300.bin'  # 模型下载正确路径
    embedding_model = KeyedVectors.load_word2vec_format(model_path, binary=True)
except Exception as e:
    logging.error(f"加载Word2Vec模型失败: {e}")

# 从JSON加载数据
try:
    with open('my_data.json', 'r') as file:
        data = json.load(file)
except Exception as e:
    logging.error(f"加载JSON数据错误: {e}")
    data = []

def simulate_rag(data, prompt):
    matches = []
    threshold = 0.4  # 余弦相似度示例阈值
    prompt_embedding = compute_embeddings(prompt, embedding_model)
    for passage in data:
        combined_text = f"{passage['title']} {passage['content']}".lower()
        passage_embedding = compute_embeddings(combined_text, embedding_model)
        similarity = np.dot(prompt_embedding, passage_embedding) / (np.linalg.norm(prompt_embedding) * np.linalg.norm(passage_embedding))
        print(f"passage: {passage}")
        print(f"Similarity: {similarity}")
        if similarity > threshold:
            matches.append(passage)
    return matches[:2]  # 返回前2个检索的段落

prompt = "Nedved Yang喜欢吃什么?你能推荐新加坡的哪个地方给他吃吗?"


# 从本地数据检索相关段落
retrieved_passages = simulate_rag(data, prompt)
print(f"**检索到的段落:**\n{retrieved_passages}")

# 构建LLM提示
llm_prompt = f"用户查询: {prompt}\n\n检索到的信息:\n"
for passage in retrieved_passages:
    llm_prompt += f"- {passage['title']}:\n  - {passage['content']}\n  - 来源: {passage['source']}\n"

print(f"**LLM提示:**\n{llm_prompt}")
llm = Ollama(model="gemma:2b")
llm_response = llm.invoke(llm_prompt)  # 替换您的LLM交互方法
final_response = f"**LLM回应:**\n{llm_response}"
 # 打印最终回应
print(final_response)

在使用word2vec进行本地嵌入前,您需要从网上下载它,例如从​​​​​​https://github.com/harmanpreet93/load-word2vec-google?tab=readme-ov-file。然后,您可以加载它来计算嵌入。我遇到了一个问题,即`retrieved_passages`返回为空。通过下面的手动测试,我发现根本原因是相似度低于阈值。

复制代码
# 示例手动测试

prompt_embedding = compute_embeddings("Nedved Yang喜欢吃什么?", embedding_model)
example_entry = "Nedved Yang喜欢辛辣和素食菜肴。"
entry_embedding = compute_embeddings(example_entry, embedding_model)
similarity = np.dot(prompt_embedding, entry_embedding) / (np.linalg.norm(prompt_embedding) * np.linalg.norm(entry_embedding))
print(f"Similarity: {similarity}")

在调整阈值后,来自Gemma的回应看起来不错。

试试看,玩得开心!

相关推荐
扫地的小何尚14 小时前
NVIDIA CUDA-Q QEC权威指南:实时解码、GPU解码器与AI推理增强
人工智能·深度学习·算法·llm·gpu·量子计算·nvidia
hy156878614 小时前
COZE编程-智能体-起飞起飞起飞(一句话生成智能体大升级)
人工智能·coze·自动编程
人工智能培训14 小时前
深度学习初学者指南
人工智能·深度学习·群体智能·智能体·人工智能培训·智能体搭建·深度学习培训
Luke Ewin14 小时前
基于FunASR开发的可私有化部署的语音转文字接口 | FunASR接口开发 | 语音识别接口私有化部署
人工智能·python·语音识别·fastapi·asr·funasr
龙山云仓14 小时前
No095:沈括&AI:智能的科学研究与系统思维
开发语言·人工智能·python·机器学习·重构
LiYingL14 小时前
多人对话视频生成的新发展:麻省理工学院数据集和基线模型 “CovOG
人工智能
人工智能培训14 小时前
DNN案例一步步构建深层神经网络(二)
人工智能·神经网络·大模型·dnn·具身智能·智能体·大模型学习
TG:@yunlaoda360 云老大14 小时前
华为云国际站代理商的GACS主要有什么作用呢?
人工智能·自然语言处理·华为云
AI营销资讯站14 小时前
原圈科技AI营销内容生产体系助力企业降本提效新变革
大数据·人工智能
AI科技星14 小时前
质量定义方程中条数概念的解析与经典例子计算
数据结构·人工智能·经验分享·算法·计算机视觉