搜索
首页后端开发Python教程使用 Ollama 实现矢量搜索的部分

Part Implementing Vector Search with Ollama

第 1 部分介绍了使用 pgvector 设置的 PostgreSQL,第 2 部分使用 OpenAI 嵌入实现了向量搜索。最后一部分演示如何使用 Ollama 在本地运行矢量搜索! ✨


内容

  • 内容
  • 为什么是奥拉马?
  • 使用 Docker 设置 Ollama
  • 数据库更新
  • 实施
  • 搜索查询
  • 性能提示
  • 故障排除
  • OpenAI 与 Ollama
  • 总结

为什么是奥拉马? ?

Ollama 允许您在本地运行 AI 模型:

  • 离线操作,更好的数据隐私
  • 无 API 成本
  • 快速响应时间

我们将在 Ollama 中使用 nomic-embed-text 模型,该模型创建 768 维向量(相比之下 OpenAI 为 1536 维)。

使用 Docker 设置 Ollama ?

要将 Ollama 添加到您的 Docker 设置中,请将此服务添加到 compose.yml:

services:
  db:
    # ... (existing db service)

  ollama:
    image: ollama/ollama
    container_name: ollama-service
    ports:
      - "11434:11434"
    volumes:
      - ollama_data:/root/.ollama

  data_loader:
    # ... (existing data_loader service)
    environment:
      - OLLAMA_HOST=ollama
    depends_on:
      - db
      - ollama

volumes:
  pgdata:
  ollama_data:

然后,启动服务并拉取模型:

docker compose up -d

# Pull the embedding model
docker compose exec ollama ollama pull nomic-embed-text

# Test embedding generation
curl http://localhost:11434/api/embed -d '{
  "model": "nomic-embed-text",
  "input": "Hello World"
}'

数据库更新?

更新数据库以存储 Ollama 嵌入:

-- Connect to the database
docker compose exec db psql -U postgres -d example_db

-- Add a column for Ollama embeddings
ALTER TABLE items
ADD COLUMN embedding_ollama vector(768);

对于全新安装,请更新 postgres/schema.sql:

CREATE TABLE items (
    id SERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    item_data JSONB,
    embedding vector(1536),        # OpenAI
    embedding_ollama vector(768)   # Ollama
);

执行 ?

更新requirements.txt以安装Ollama Python库:

ollama==0.3.3

以下是 load_data.py 的示例更新,用于添加 Ollama 嵌入:

import ollama  # New import

def get_embedding_ollama(text: str):
    """Generate embedding using Ollama API"""
    response = ollama.embed(
        model='nomic-embed-text',
        input=text
    )
    return response["embeddings"][0]

def load_books_to_db():
    """Load books with embeddings into PostgreSQL"""
    books = fetch_books()

    for book in books:
        description = (
            f"Book titled '{book['title']}' by {', '.join(book['authors'])}. "
            f"Published in {book['first_publish_year']}. "
            f"This is a book about {book['subject']}."
        )

        # Generate embeddings with both OpenAI and Ollama
        embedding = get_embedding(description)                # OpenAI
        embedding_ollama = get_embedding_ollama(description)  # Ollama

        # Store in the database
        store_book(book["title"], json.dumps(book), embedding, embedding_ollama)

请注意,为了清楚起见,这是一个简化版本。完整的源代码在这里。

如您所见,Ollama API 结构与 OpenAI 类似!

搜索查询 ?

使用 Ollama 嵌入检索相似项目的搜索查询:

-- View first 5 dimensions of an embedding
SELECT
    name,
    (replace(replace(embedding_ollama::text, '[', '{'), ']', '}')::float[])[1:5] as first_dimensions
FROM items;

-- Search for books about web development:
WITH web_book AS (
    SELECT embedding_ollama FROM items WHERE name LIKE '%Web%' LIMIT 1
)
SELECT
    item_data->>'title' as title,
    item_data->>'authors' as authors,
    embedding_ollama  (SELECT embedding_ollama FROM web_book) as similarity
FROM items
ORDER BY similarity
LIMIT 3;

性能提示?

添加索引

CREATE INDEX ON items
USING ivfflat (embedding_ollama vector_cosine_ops)
WITH (lists = 100);

资源要求

  • RAM:该型号约 2GB
  • 第一个查询:模型加载预计会有轻微延迟
  • 后续查询:~50ms 响应时间

GPU支持

如果处理大型数据集,GPU 支持可以大大加快嵌入生成速度。详情请参考 Ollama Docker 镜像。

故障排除?

连接被拒绝错误

Ollama 图书馆需要知道在哪里可以找到 Ollama 服务。在 data_loader 服务中设置 OLLAMA_HOST 环境变量:

data_loader:
  environment:
    - OLLAMA_HOST=ollama

找不到型号错误

手动拉取模型:

docker compose exec ollama ollama pull nomic-embed-text

或者,您可以添加一个脚本,使用 ollama.pull() 函数在 Python 代码中自动拉取模型。点击此处了解更多详情。

高内存使用率

  • 重启 Ollama 服务
  • 考虑使用较小的模型

OpenAI 与 Ollama ⚖️

Feature OpenAI Ollama
Vector Dimensions 1536 768
Privacy Requires API calls Fully local
Cost Pay per API call Free
Speed Network dependent ~50ms/query
Setup API key needed Docker only

包起来 ?

本教程仅介绍如何使用 Ollama 设置本地矢量搜索。现实世界的应用程序通常包含附加功能,例如:

  • 查询优化和预处理
  • 混合搜索(与全文搜索相结合)
  • 与网络界面集成
  • 安全和性能考虑因素

完整的源代码,包括使用 FastAPI 构建的简单 API,可在 GitHub 上获取。欢迎 PR 和反馈!

资源:

  • Ollama 文档
  • Ollama Python 库
  • Ollama 嵌入模型

有问题或反馈吗?请在下面发表评论! ?

以上是使用 Ollama 实现矢量搜索的部分的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python的混合方法:编译和解释合并Python的混合方法:编译和解释合并May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

了解python的' for”和' then”循环之间的差异了解python的' for”和' then”循环之间的差异May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串联列表与重复Python串联列表与重复May 08, 2025 am 12:09 AM

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

Python列表串联性能:速度比较Python列表串联性能:速度比较May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何将元素插入python列表中?您如何将元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表动态阵列或引擎盖下的链接列表?Python是否列表动态阵列或引擎盖下的链接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何从python列表中删除元素?如何从python列表中删除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器