ChromaDB调用BGE模型的两种实践方式

ChromaDB调用BGE模型

前言

在语义搜索、知识库构建等场景中,文本向量化(Embedding)是核心技术环节。作为一款开源的向量数据库,ChromaDB允许开发者通过自定义嵌入函数灵活对接各类模型。本文将详细介绍两种基于BGE模型的实现方案:​​远程API调用​​与​​本地模型部署​​,并解析它们的应用场景与实现细节。

1.chromadb调用BGE模型api

此api接口是Ollama接口方式:

关键点解析:

​​API服务对接​​:通过HTTP POST请求调用部署在9.1.47.89:11434的Ollama服务

​​模型指定​​:使用bge-m3:latest模型的最新版本

​​超时控制​​:设置30秒超时避免长期阻塞

​​异常处理​​:非200状态码时抛出详细错误信息

python 复制代码
import requests
from chromadb.api.types import Documents, EmbeddingFunction, Embeddings

class MyEmbeddingFunction(EmbeddingFunction):
    def __call__(self, texts: Documents) -> Embeddings:
        # 调用远程Ollama服务的BGE-M3模型
        response = requests.post(
            "http://9.1.47.89:11434/v1/embeddings",
            json={
                "model": "bge-m3:latest",
                "input": texts
            },
            timeout=30  # 增加超时设置
        )
        
        if response.status_code == 200:
            return [vec['embedding'] for vec in response.json()['data']]
        else:
            raise Exception(f"Embedding API调用失败: {response.text}")

# 初始化自定义嵌入函数
ef = MyEmbeddingFunction()

注意不同版本之间的访问方式可能不一致。"http://9.1.47.89:11434/v1/embeddings",可修改为"http://9.1.47.89:11434/api/embeddings"。

vec\['embedding'\] for vec in response.json()\['data'\]\]中的"data"可修改为"embeddings"。 都可进行尝试。 ### 2.调用本地模型 ```python from chromadb.api.types import Documents, EmbeddingFunction, Embeddings from sentence_transformers import SentenceTransformer model_path = "emmodel/bge-large-zh-v1.5" model = SentenceTransformer(model_name_or_path=model_path) class MyEmbeddingFunction(EmbeddingFunction): def __call__(self, texts: Documents) -> Embeddings: embeddings = [model.encode(x).tolist() for x in texts] return embeddings ef = MyEmbeddingFunction() ``` 关键点解析: ​​本地模型加载​​:使用sentence-transformers库加载预训练模型 ​​路径指定​​:从emmodel/目录加载bge-large-zh-v1.5模型文件 ​​批量编码​​:对输入文本列表进行并行向量化 模型准备: ```python # 下载官方模型 git clone https://www.modelscope.cn/company/BAAI/bge-large-zh-v1.5.git # 或使用huggingface-hub from huggingface_hub import snapshot_download snapshot_download(repo_id="BAAI/bge-large-zh-v1.5") ```

相关推荐
摸鱼仙人~6 天前
实战 BGE-M3 与 Ollama:从接口测试到向量原理解析
ollama·bge
北京地铁1号线13 天前
BGE模型架构与训练技术
架构·向量化·bge
坐吃山猪24 天前
ChromaDB02-代码实战
数据库·向量数据库·chromadb
坐吃山猪25 天前
ChromaDB01-运行向量数据库
数据库·向量数据库·chromadb
schinber1 个月前
如何使用LangChain开发RAG系统:从理论到实践
langchain·rag·chromadb
Robot侠1 个月前
赋予 AI 记忆:在 RTX 3090 上搭建本地 RAG 知识库问答系统
人工智能·langchain·llm·llama·qwen·rag·chromadb
一粒马豆5 个月前
chromadb使用hugging face模型时利用镜像网站下载注意事项
python·embedding·chroma·词嵌入·hugging face·词向量·chromadb
之之为知知6 个月前
Chromadb 1.0.15 索引全解析:从原理到实战的向量检索优化指南
人工智能·深度学习·机器学习·大模型·索引·向量数据库·chromadb
仙人掌_lz9 个月前
为特定领域微调嵌入模型:打造专属的自然语言处理利器
人工智能·ai·自然语言处理·embedding·强化学习·rl·bge