国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Elasticsearch:使用在本地計算機上運行的 LLM 以及 Ollama 和 Langchain 構建 RAG 應用程序

這篇具有很好參考價值的文章主要介紹了Elasticsearch:使用在本地計算機上運行的 LLM 以及 Ollama 和 Langchain 構建 RAG 應用程序。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

無需 GPU 的隱私保護 LLM。在本博客中,我將演示使用不同的工具 Ollama 構建的 RAG 應用程序。 與本文相關的所有源代碼均已發(fā)布在 github上。 請克隆存儲庫以跟隨文章操作。我們可以通過如下的方式來克?。?/p>

git clone https://github.com/liu-xiao-guo/ollama_es

什么是? Ollama?

Ollama 是一個輕量級且靈活的框架,專為在個人計算機上本地部署 LLM 而設計。 它通過直觀的 API 簡化了 LLMs 的開發(fā)、執(zhí)行和管理,并提供了一系列預配置模型,可立即在各種應用程序中使用。 其設計的核心是將模型權重、配置和數(shù)據(jù)捆綁到一個統(tǒng)一的包中,并封裝在模型文件中。

該框架具有一系列精選的預量化、優(yōu)化模型,例如 Llama 2、Mistral 和 Gemma,可供部署。 這些模型經(jīng)過專門設計,可在標準消費類硬件(涵蓋 CPU 和 GPU)上運行,并且與多種操作系統(tǒng)兼容,包括 macOS、Linux 和 Windows。 這種方法消除了用戶自己承擔復雜的模型優(yōu)化任務的必要性。

鑒于 LLMs 因其規(guī)模龐大而通常需要強大的 GPU 來進行操作,Ollama 支持的模型采用神經(jīng)網(wǎng)絡量化。 這項技術極大地降低了硬件要求,使 LLMs 能夠在沒有互聯(lián)網(wǎng)連接的情況下在常見計算設備上高效運行。 因此,Ollama 使 LLM 技術變得更容易使用,使個人和組織能夠在消費級硬件上利用這些先進的模型。

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能
Ollama

RAG 應用

該 RAG 應用程序包含一個定制的數(shù)據(jù)集,該數(shù)據(jù)集是從在線網(wǎng)站動態(tài)抓取的。 用戶可以通過 API(例如 REST API)與網(wǎng)站數(shù)據(jù)進行交互。 出于演示目的,我們選擇了 Open5GS 文檔網(wǎng)站(Open5GS 是 5G Core 的 C 語言實現(xiàn))。 Open5GS 文檔中的數(shù)據(jù)被抓取、分割,然后作為向量嵌入存儲在 Elasticsearch?向量數(shù)據(jù)庫中。 因此,用戶可以通過 API 與 Open5GS 文檔的內(nèi)容無縫交互。

對于此 RAG 應用程序的 LLM 組件,我選擇了 Llama2 7B 模型,該模型通過 Ollama 運行。 在 Ollama 上運行的 Llama2 是 Meta 的基于 Llama-2 的 LLM,經(jīng)過量化以在消費級硬件(例如 CPU)上實現(xiàn)最佳性能。 在此 RAG 應用程序中,與 Ollama 一起運行的 Llama2 LLM 根據(jù) Open5GS 文檔中的內(nèi)容提供用戶問題的答案。 通過 Langchain 促進了 RAG 應用程序和 LLM 的集成。

以下是 RAG 應用程序的主要功能。 下圖詳細介紹了包含這些不同組件的綜合功能架構。

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

1. 抓取網(wǎng)絡數(shù)據(jù)

Langchain 提供不同類型的文檔加載器來加載不同來源的數(shù)據(jù)作為文檔。 RecursiveUrlLoader 就是這樣一種文檔加載器,可用于將 Web url 中的數(shù)據(jù)加載到文檔中。 此步驟使用 Langchain 的 RecursiveUrlLoader 從網(wǎng)絡上抓取數(shù)據(jù)作為文檔。 RecursiveUrlLoader 遞歸地將給定的 url 抓取到給定的 max_depth 并讀取網(wǎng)絡上的數(shù)據(jù)。 該數(shù)據(jù)用于創(chuàng)建向量嵌入并回答用戶的問題。

2. 分割文檔

處理較長的文本時,必須將文本分成較小的片段。 盡管這項任務看起來很簡單,但它可能包含相當復雜的內(nèi)容。 目標是確保語義相關的文本片段保持在一起。 Langchain 文本分割器有效地完成了這項任務。 本質上,它將文本劃分為小的、具有語義意義的單元(通常是句子)。 然后將這些較小的片段組合起來形成較大的塊,直到它們達到由特定函數(shù)確定的特定大小。 達到此大小后,該塊將被指定為單獨的文本片段,并且該過程會再次以一些重疊的方式開始。 對于這個特定的場景,我使用了 RecursiveCharacterTextSplitter 將抓取的文檔分割成可管理的塊。

3. 創(chuàng)建向量嵌入

收集并分割數(shù)據(jù)后,下一步是將文本信息轉換為向量嵌入。 然后根據(jù)分割數(shù)據(jù)創(chuàng)建這些嵌入。 文本嵌入對于 LLM 操作的運作至關重要。 雖然使用自然語言處理語言模型在技術上是可行的,但存儲和檢索此類數(shù)據(jù)的效率非常低。 為了提高效率,有必要將文本數(shù)據(jù)轉換為向量形式。 有專門為從文本創(chuàng)建嵌入而設計的專用機器學習模型。 在本例中,我使用開源 HuggingFaceEmbedding 模型 all-MiniLM-L6-v2 來生成向量嵌入。 因此,文本被轉換為多維向量,這些向量本質上是捕獲語義含義和上下文細微差別的高維數(shù)字表示。 嵌入后,可以對這些數(shù)據(jù)進行分組、排序、搜索等。 我們可以計算兩個句子之間的距離來確定它們的相關程度。 重要的是,這些操作超越了依賴關鍵字的傳統(tǒng)數(shù)據(jù)庫搜索,而是捕獲句子之間的語義接近度。

4. 將向量嵌入存儲在 Elasticsearch 中

然后生成的向量嵌入存儲在 Elasticsearch?向量數(shù)據(jù)庫中。Elasticsearch 是一個開放及免費的嵌入數(shù)據(jù)庫,通過存儲和檢索嵌入及其元數(shù)據(jù)以及文檔和查詢,可以輕松構建 LLM 應用程序。 Elasticsearch?可以有效地處理這些嵌入,從而可以快速檢索和比較基于文本的數(shù)據(jù)。 傳統(tǒng)數(shù)據(jù)庫在精確查詢方面效果很好,但在理解人類語言的細微差別方面卻表現(xiàn)不佳。 輸入向量數(shù)據(jù)庫,它是處理語義搜索的游戲規(guī)則改變者。 與依賴于精確單詞或短語的傳統(tǒng)文本匹配不同。

5. 用戶提問

系統(tǒng)提供API,用戶可以通過該 API 提交問題。 在此用例中,用戶可以提出與 Open5GS 文檔內(nèi)容相關的任何問題。 該 API 充當用戶和聊天機器人之間交互的主要接口。 該 API 采用一個參數(shù) user_id,用于標識不同的用戶會話。 此 user_id 用于演示目的。 在現(xiàn)實場景中,可以使用 HTTP 請求中的授權標頭(例如 JWT Bearer 令牌)進行管理。 該 API 的設計直觀且易于訪問,使用戶能夠輕松輸入查詢并接收響應。

6. 創(chuàng)建問題的向量嵌入

當用戶通過 API 提交問題時,系統(tǒng)會將該問題轉換為向量嵌入。 嵌入的生成由 ConversationalRetrievalChain 自動處理。 這有利于向量數(shù)據(jù)庫內(nèi)與問題相關的文檔的語義搜索。

7. 語義搜索向量數(shù)據(jù)庫

創(chuàng)建問題的向量嵌入后,系統(tǒng)會使用語義搜索來掃描向量數(shù)據(jù)庫,識別與用戶查詢最相關的內(nèi)容。 通過將問題的向量嵌入與存儲的數(shù)據(jù)的向量嵌入進行比較,系統(tǒng)可以準確地查明上下文相似或與查詢相關的信息。 在這種情況下,我使用了 ConversationalRetrievalChain,它根據(jù)輸入查詢自動處理語義搜索。 然后,語義搜索的結果將被識別為 LLM 的上下文。

8. 生成提示

接下來,ConversationalRetrievalChain 會根據(jù)用戶的問題和語義搜索結果(上下文)生成自定義提示。 語言模型的提示是用戶提供的一組指令或輸入,用于指導模型的響應。 這有助于模型理解上下文并生成相關且連貫的基于語言的輸出,例如回答問題、完成句子或參與對話。

9. 向 LLM 提交提示

生成提示后,它會通過 Langchain 庫 Ollama(Langchain 在 langchain_community.llms 中正式支持 Ollama)發(fā)布到 LLM(在我們的示例中為 Llama2 7B)。 然后, LLM 根據(jù)提供的上下文找到問題的答案。 ConversationalRetrievalChain 處理將查詢發(fā)布到 LLM 的功能。

10. LLM 生成答案

LLM 利用 Meta 的 Llama-2 的高級功能,在所提供內(nèi)容的上下文中處理問題。 然后它生成響應并將其發(fā)回。

11. 在 MongoDB 聊天記錄中保存查詢和響應

Langchain 提供了各種用于管理會話內(nèi)存的組件。 在這個聊天機器人中,MongoDB 用于會話內(nèi)存的管理。 在此階段,用戶的問題和聊天機器人的響應都作為聊天歷史記錄的一部分記錄在 MongoDB 存儲中。 這種方法確保所有用戶聊天歷史記錄都持久存儲在 MongoDB 中,從而能夠檢索以前的交互。 數(shù)據(jù)按每個用戶會話存儲在 MongoDB 中。 為了區(qū)分用戶會話,API 使用 user_id 參數(shù),如前所述。 這些歷史數(shù)據(jù)對于塑造未來的互動至關重要。 當同一用戶提出后續(xù)問題時,聊天歷史記錄以及新的語義搜索結果(上下文)將被轉發(fā)給 LLMs。 此過程保證聊天機器人可以在整個對話過程中保持上下文,從而產(chǎn)生更精確和定制的響應。

在本例中,我們沒有完成這個部分的功能。在實際的操作中,我們也可以使用 Elasticsearch 來代替 MongoDB 來完成這個功能。

12. 將答案發(fā)送回用戶

最后,從 LLM 收到的響應通過 HTTP API 轉發(fā)給用戶。 用戶可以通過提供相同的 user_id 在后續(xù)請求中繼續(xù)提出不同的問題。 然后,系統(tǒng)會識別用戶的聊天歷史記錄,并將其與新的語義搜索結果一起包含在發(fā)送給 LLM 的信息中。 此過程可確保無縫且上下文相關的對話,從而豐富每次交互的用戶體驗。

安裝

?安裝 Elasticsarch 及 Kibana

如果你還沒有安裝好自己的 Elasticsearch 及 Kibana,請參考如下的鏈接來進行安裝:

  • 如何在 Linux,MacOS 及 Windows 上進行安裝 Elasticsearch
  • Kibana:如何在 Linux,MacOS 及 Windows上安裝 Elastic 棧中的 Kibana

在安裝的時候,我們選擇 Elastic Stack 8.x 來進行安裝。特別值得指出的是:ES|QL 只在 Elastic Stack 8.11 及以后得版本中才有。你需要下載 Elastic Stack 8.11 及以后得版本來進行安裝。

在首次啟動 Elasticsearch 的時候,我們可以看到如下的輸出:

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

安裝 Python 依賴包

我們在項目的根目錄下使用如下的命令來創(chuàng)建虛擬的環(huán)境:

python3 -m venv .venv
source .venv/bin/activate

我們?nèi)缓笤谔摂M的環(huán)境中打入如下的命令:

pip3 install -r requirements.txt

拷貝 Elasticsearch 證書

我們可以通過如下的方式把? Elasticsearch 的證書拷貝到當前的項目根目錄下:

(.venv) $ pwd
/Users/liuxg/python/ollama
(.venv) $ cp ~/elastic/elasticsearch-8.12.0/config/certs/http_ca.crt .
overwrite ./http_ca.crt? (y/n [n]) 

你需要根據(jù)自己的證書的位置進行調(diào)整。

創(chuàng)建環(huán)境變量

我們在項目的當前根目錄下,創(chuàng)建一個叫做 .env 的文件:

INIT_INDEX=true
TARGET_URL="https://open5gs.org/open5gs/docs/"
HTTP_PORT=7654
ES_USER="elastic"
ES_PASSWORD="hBZtXFwhz3HCtLi-cVc5"
ES_ENDPOINT="localhost"
(.venv) $ pwd
/Users/liuxg/python/ollama
(.venv) $ ls .env
.env
(.venv) $ cat .env
INIT_INDEX=true
TARGET_URL="https://open5gs.org/open5gs/docs/"
HTTP_PORT=7654
ES_USER="elastic"
ES_PASSWORD="hBZtXFwhz3HCtLi-cVc5"
ES_ENDPOINT="localhost"

它的內(nèi)容如上。你需要根據(jù)自己的 Elasticsearch 配置進行相應的修改。

實施

下面詳細介紹該 ChatBot 的完整實現(xiàn)。 ChatBot 代理的完整源代碼可在 github?上訪問和查看。

1)?配置

在 config.py 文件中,我定義了 ChatBot 中使用的各種配置。?

config.py

import os
from dotenv import load_dotenv
from elasticsearch import Elasticsearch, helpers

load_dotenv()

# define init index
INIT_INDEX = os.getenv('INIT_INDEX', 'false').lower() == 'true'

# target url to scrape
TARGET_URL =  os.getenv('TARGET_URL', "https://open5gs.org/open5gs/docs/")

# http api port
HTTP_PORT = os.getenv('HTTP_PORT', 7654)

ES_USER = os.getenv("ES_USER")
ES_PASSWORD = os.getenv("ES_PASSWORD")
ES_ENDPOINT = os.getenv("ES_ENDPOINT")

elastic_index_name = "ollama_index"

url = f"https://{ES_USER}:{ES_PASSWORD}@{ES_ENDPOINT}:9200"

connection = Elasticsearch(
    hosts=[url], 
    ca_certs = "./http_ca.crt", 
    verify_certs = True
    )

2)?模型 - model

下面是模型的實現(xiàn)。 它包含一個函數(shù) init_index,該函數(shù)從給定的 Web URL 中抓取數(shù)據(jù)并創(chuàng)建向量存儲。 環(huán)境變量 INIT_INDEX 用于確定是否創(chuàng)建索引。 init_conversation 函數(shù)使用 Ollama 的 Llama2 LLM 初始化 ConversationalRetrievalChain,可通過 Ollama 的模型 REST API <host>:11434 獲?。∣llama 提供用于與 LLM 交互的 REST API。有關如何使用此功能的詳細說明和更多信息,請參閱到 Run Ollama Llama2 部分)。 聊天功能負責向 LLM 發(fā)送問題。

model.py

from langchain_community.llms import Ollama
from langchain_community.chat_models import ChatOpenAI
from langchain_community.document_loaders import PyPDFLoader
from langchain.document_loaders.recursive_url_loader import RecursiveUrlLoader
from langchain_community.embeddings import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory
from langchain_community.vectorstores import ElasticsearchStore
from langchain_community.embeddings import HuggingFaceEmbeddings
from bs4 import BeautifulSoup as Soup
from langchain.utils.html import (PREFIXES_TO_IGNORE_REGEX,
                                  SUFFIXES_TO_IGNORE_REGEX)

from elasticsearch import Elasticsearch, helpers

from config import *
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

global conversation
conversation = None

global vectordb
vectordb = None

def init_index():
    global vectordb
    
    if not INIT_INDEX:
        logging.info("continue without initializing index")
        return
    
    # scrape data from web
    documents = RecursiveUrlLoader(
        TARGET_URL,
        max_depth=4,
        extractor=lambda x: Soup(x, "html.parser").text,
        prevent_outside=True,
        use_async=True,
        timeout=600,
        check_response_status=True,
        # drop trailing / to avoid duplicate pages.
        link_regex=(
            f"href=[\"']{PREFIXES_TO_IGNORE_REGEX}((?:{SUFFIXES_TO_IGNORE_REGEX}.)*?)"
            r"(?:[\#'\"]|\/[\#'\"])"
        ),
    ).load()

    logging.info("index creating with `%d` documents", len(documents))

    # split text
    # this chunk_size and chunk_overlap effects to the prompt size
    # execeed promt size causes error `prompt size exceeds the context window size and cannot be processed`
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    documents = text_splitter.split_documents(documents)
    
    # create embeddings with huggingface embedding model `all-MiniLM-L6-v2`
    # then persist the vector index on vector db
    embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
    
    if not connection.indices.exists(index=elastic_index_name):
        print("The index does not exist, going to generate embeddings")   
        vectordb = ElasticsearchStore.from_documents( 
                documents,
                embedding = embeddings, 
                es_url = url, 
                es_connection = connection,
                index_name = elastic_index_name, 
                es_user = ES_USER,
                es_password = ES_PASSWORD
        )
    else: 
        print("The index already existed")    
        vectordb = ElasticsearchStore(
            es_connection = connection,
            embedding = embeddings,
            es_url = url, 
            index_name = elastic_index_name, 
            es_user = ES_USER,
            es_password = ES_PASSWORD    
        )   

def init_conversation():
    global conversation
    global vectordb

    # llama2 llm which runs with ollama
    # ollama expose an api for the llam in `localhost:11434`
    llm = Ollama(
        model="llama2",
        base_url="http://localhost:11434",
        verbose=True,
    )

    # create conversation
    conversation = ConversationalRetrievalChain.from_llm(
        llm,
        retriever = vectordb.as_retriever(),
        return_source_documents = True,
        verbose = True,
    )

def chat(question, user_id):
    global conversation

    chat_history = []
    response = conversation({"question": question, "chat_history": chat_history})
    answer = response['answer']

    logging.info("got response from llm - %s", answer)

    # TODO save history

    return answer

3)?HTTP API

HTTP API 的實現(xiàn)在 api.py 中進行。 此 API 包括 HTTP POST 端點 api/question,它接受包含問題和 user_id 的 JSON 對象。 user_id 用于演示目的。 在實際應用程序中,這可以通過 HTTP 請求中的授權標頭(例如 JWT Bearer 令牌)進行管理。 當收到用戶的問題請求時,它會被轉發(fā)到 ChatBot 模型中的聊天功能。

from flask import Flask
from flask import jsonify
from flask import request
from flask_cors import CORS
import logging
import sys
from model import init_index
from model import init_conversation
from model import chat
from config import *

app = Flask(__name__)
CORS(app)

init_index()
init_conversation()

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

@app.route("/")
def index():
    return "<p>Hello, World!</p>"

@app.route('/api/question', methods=['POST'])
def post_question():
    json = request.get_json(silent=True)
    question = json['question']
    user_id = json['user_id']
    logging.info("post question `%s` for user `%s`", question, user_id)

    resp = chat(question, user_id)
    data = {'answer':resp}

    return jsonify(data), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=HTTP_PORT, debug=True)

運行應用

以下是操作 ChatBot 應用程序并與之交互的主要步驟。 可以使用 HTTP API 提交問題,并將收到相應的響應。

運行 Ollama LIama2

Ollama 提供了多種部署選項,使其能夠作為獨立的二進制文件在 macOS、Linux 或 Windows 以及 Docker 容器中運行。 這種靈活性確保用戶可以在自己喜歡的平臺上輕松設置 LLM 并與 LLM 進行交互。 Ollama 支持命令行和 REST API 交互,允許無縫集成到各種工作流程和應用程序中。 其實用性的一個例子是通過 Ollama 運行 Llama2 模型,展示了其有效托管和管理 LLM 的能力。 下面是使用 Docker 部署 Ollama 的示例方法,重點介紹了我在此平臺上運行 Llama2 模型的經(jīng)驗。

docker run -d -v $(PWD)/data:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
$ docker run -d -v $(PWD)/data:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
Unable to find image 'ollama/ollama:latest' locally
latest: Pulling from ollama/ollama
f4bb4e8dca02: Pull complete 
aeed191ede92: Pull complete 
920e2a93e5f4: Pull complete 
Digest: sha256:75fb97cdd8f435756d26eb7783599122b814c4b97da2012dc21ebc0efbd90fef
Status: Downloaded newer image for ollama/ollama:latest
a7a4fc0bed77b910ee30a5c200ee9a069f47e3974f91c2eda6cda67f353276bb
docker exec -it ollama bash
$ docker exec -it ollama bash
root@a7a4fc0bed77:/# ollama run llama2
pulling manifest 
pulling 8934d96d3f08... 100% ▕███████████████████████████████▏ 3.8 GB                         
pulling 8c17c2ebb0ea... 100% ▕███████████████████████████████▏ 7.0 KB                         
pulling 7c23fb36d801... 100% ▕███████████████████████████████▏ 4.8 KB                         
pulling 2e0493f67d0c... 100% ▕███████████████████████████████▏   59 B                         
pulling fa304d675061... 100% ▕███████████████████████████████▏   91 B                         
pulling 42ba7f8a01dd... 100% ▕███████████████████████████████▏  557 B                         
verifying sha256 digest 
writing manifest 
removing any unused layers 
success 
>>> /byte
Unknown command '/byte'. Type /? for help
>>> /?
Available Commands:
  /set            Set session variables
  /show           Show model information
  /load <model>   Load a session or model
  /save <model>   Save your current session
  /bye            Exit
  /?, /help       Help for a command
  /? shortcuts    Help for keyboard shortcuts

Use """ to begin a multi-line message.

>>> /bye
root@a7a4fc0bed77:/# ollama list
NAME         	ID          	SIZE  	MODIFIED       
llama2:latest	78e26419b446	3.8 GB	19 minutes ago	
root@a7a4fc0bed77:/# ollama run llama2
>>> what is docker?

Docker is a computer program that creates software containers, which are lightweight and 
portable environments for applications to run in. It was first released in 2013 by Docker
Inc., and has since become one of the most popular and widely-used containerization 
platforms.

Docker allows developers to package an application and its dependencies into a single 
container that can be run on any system that has Docker installed, regardless of the 
underlying architecture or operating system. This makes it easy to deploy applications 
across different environments, such as from development to testing to production, without
worrying about compatibility issues.

Here are some key features of Docker:

1. Containerization: Docker creates lightweight containers for applications, which 
includes everything an application needs to run, including code, libraries, and 
dependencies.
2. Portability: Docker containers are platform-independent, meaning they can be run on 
any system that has Docker installed, regardless of the underlying architecture or 
operating system.
3. Isolation: Docker containers are isolated from each other and from the host system, 
which means they do not interfere with each other or access sensitive information outside
of their own container.
4. Efficiency: Docker containers use less resources than traditional virtualization 
methods, making them faster to spin up and more efficient in terms of memory and CPU 
usage.
5. Security: Docker provides a secure environment for applications by isolating them from
the host system and limiting access to sensitive resources.
6. Networking: Docker provides a built-in networking system that allows containers to 
communicate with each other and with external services.
7. Version control: Docker allows developers to manage different versions of their 
applications by creating and managing different containers for each version.
8. Collaboration: Docker makes it easy for multiple developers to work on the same 
application by allowing them to create and share containers.
9. Automated workflows: Docker provides a range of tools for automating the deployment 
and management of applications, such as continuous integration and continuous deployment 
(CI/CD) pipelines.

Docker is used in a variety of industries and use cases, including:
...
>>> exit
>>> exit

Thank you for using Docker! If you have any questions or need further assistance, feel 
free to ask. Otherwise, it was nice working with you. Have a great day and happy coding! ??

>>> /bye
root@a7a4fc0bed77:/# exit
exit
$ curl http://localhost:11434/api/generate -d '{
>   "model": "llama2",
>   "prompt": "what is docker?",
>   "stream": true
> }'
{"model":"llama2","created_at":"2024-03-24T10:50:52.97276476Z","response":"\n","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.118271052Z","response":"D","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.262979052Z","response":"ocker","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.40882826Z","response":" is","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.554231219Z","response":" an","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.69958351Z","response":" open","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.844950552Z","response":"-","done":false}
{"model":"llama2","created_at":"2024-03-24T10:50:53.989866969Z","response":"source","done":false}
 ....

我們可以在另外一個 termnial 中打入如下的命令:

curl http://localhost:11434/api/generate -d '{
  "model": "llama2",
  "prompt": "what is docker?",
  "stream": true
}'
$ curl http://localhost:11434/api/generate -d '{
>   "model": "llama2",
>   "prompt": "what is docker?",
>   "stream": true
> }'
{"model":"llama2","created_at":"2024-03-24T10:54:20.300787717Z","response":"\n","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:20.453422759Z","response":"D","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:20.598751134Z","response":"ocker","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:20.744523634Z","response":" is","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:20.890211551Z","response":" a","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:21.035385717Z","response":" container","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:21.179915259Z","response":"ization","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:21.324945884Z","response":" platform","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:21.469440676Z","response":" that","done":false}
{"model":"llama2","created_at":"2024-03-24T10:54:21.614479718Z","response":" allows","done":false}
^C

我們也可以使用如下的命令來進行測試:

$ curl http://localhost:11434/api/generate -d '{
  "model": "llama2",
  "prompt": "what is docker?",
  "stream": false
}'
{"model":"llama2","created_at":"2024-03-24T10:55:44.499693339Z","response":"\nDocker is an open-source platform that enables you to create, deploy, and run applications in containers. Containers are lightweight and portable, and they provide a consistent and reliable way to deploy applications across different environments. Docker allows developers and IT professionals to package an application and its dependencies into a single container, which can be easily deployed and run on any system that supports Docker, regardless of the underlying infrastructure.\n\nDocker provides several benefits, including:\n\n1. Isolation: Containers are isolated from each other and the host system, which means that if one container crashes or is compromised, it won't affect other containers or the host system.\n2. Portability: Containers are portable, meaning they can be deployed on any system that supports Docker, regardless of the underlying infrastructure.\n3. Faster deployment: With Docker, you can deploy applications faster because containers are smaller and easier to set up than traditional virtual machines.\n4. Easier collaboration: Docker makes it easier for developers to collaborate on applications because containers can be easily shared and reproduced across different environments.\n5. Improved security: Containers provide a consistent and predictable environment, which can help improve application security by reducing the risk of vulnerabilities and attacks.\n6. Scalability: Docker allows you to scale applications more easily by creating multiple containers that can be scaled independently.\n7. Better resource utilization: Docker allows you to make better use of system resources because containers are lightweight and do not require a separate operating system for each application.\n8. Simplified backup and recovery: With Docker, you can easily create backups of your applications and restore them in case of a failure or disaster.\n9. Improved testing and development: Do

請注意:在上面的命令運行后,可能需要一個較長的時間才能得到響應。你需要耐心等待。

運行 RAG 應用

RAG 應用程序可以通過 api.py 啟動,如下所述。 在運行之前,有必要通過環(huán)境變量設置一些配置。 app.py 執(zhí)行后,它將啟動 HTTP API,使用戶能夠發(fā)布他們的問題。

我們可以使用如下的命令來設置 flask 應用:

export FLASK_APP=api.py
flask run

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

上面顯示我們的服務器運行于地址 http://127.0.0.1:5000。

在運行完上面的命令后,我們可以到 Kibana 中進行查看:

GET ollama_index/_search

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

我們可以看到有 361 個文檔被寫入到 Elasticsearch 中。

為了驗證我們的 flask 服務器是否已經(jīng)正常運行,我們可以在瀏覽器中打入如下的地址。

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

很顯然我們的服務器是運行正常的。

我們在另外一個 terminal 中打入如下的命令:

curl -i -XPOST "http://127.0.0.1:5000/api/question" \
--header "Content-Type: application/json" \
--data '
{
  "question": "what is open5gs",
  "user_id": "kakka"
}
'

我們在 flask 運行的 terminal 中可以看到如下的畫面:

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

依賴于你的電腦的運行速度,等一小段的時間,我們可以看到如下的結果:

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

我們再嘗試做一個查詢:

curl -i -XPOST "http://127.0.0.1:5000/api/question" \
--header "Content-Type: application/json" \
--data '
{
  "question": "what is EPC",
  "user_id": "kakka"
}
'

ollama+rag,Elasticsearch,AI,Elastic,langchain,elasticsearch,大數(shù)據(jù),搜索引擎,全文檢索,數(shù)據(jù)庫,人工智能

請在地址下載所有的源碼?GitHub - liu-xiao-guo/ollama_es文章來源地址http://www.zghlxwxcb.cn/news/detail-853097.html

到了這里,關于Elasticsearch:使用在本地計算機上運行的 LLM 以及 Ollama 和 Langchain 構建 RAG 應用程序的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包