WeHelp
Ollama 是免費且開源的本地大型語言模型(LLM)運行框架。可以下載、安裝、執行各種開源 AI 模型。
  1. 簡介、用途說明
  2. 下載、安裝、快速使用
  3. 模型管理功能
  4. LLM API 串接
  5. Embed API 串接
Embed API 串接
## Embedding 是什麼? Embedding(嵌入向量)是將文字、圖片或其他資料轉換成一組數字向量,例如: ```text 「今天天氣很好」 → [0.12, -0.03, 0.88, ...] ``` 這些向量通常能保留資料的語意特徵,因此語意相近的文字,其向量距離也通常較接近。 ### 常見用途 1. **語意搜尋** - 使用者搜尋「如何退貨」 - 即使文件內容寫的是「退款流程」,也可能被找到 2. **RAG(Retrieval-Augmented Generation)** - 將公司文件轉成 Embedding 並存入向量資料庫 - 使用者提問時,先找出最相關的文件,再交給 LLM 回答 3. **文件相似度比較** - 比較兩段文字是否表達相近意思 4. **文件分類與聚類** - 將新聞、客服問題或商品描述依語意自動分群 5. **推薦系統** - 比較使用者興趣與商品、文章或影片的語意相似度 Embedding 模型主要負責「轉換成向量」,不負責像聊天模型一樣產生完整回答。 --- ## 使用 Ollama 提供本地端 Embedding API ### 1. 安裝並啟動 Ollama 請先安裝 Ollama: <https://ollama.com/> 啟動 Ollama 服務: ```bash ollama serve ``` 另開一個終端機,下載 Embedding 模型,例如: ```bash ollama pull nomic-embed-text ``` Ollama 預設 API 位址為: ```text http://localhost:11434 ``` 目前可使用的 Embedding API Endpoint: ```text POST http://localhost:11434/api/embed ``` --- ## 2. Python API 串接範例 先安裝 `requests`: ```bash pip install requests ``` 建立 `embedding_example.py`: ```python import requests OLLAMA_URL = "http://localhost:11434/api/embed" MODEL_NAME = "nomic-embed-text" text = "Ollama 可以在本地端執行大型語言模型。" response = requests.post( OLLAMA_URL, json={ "model": MODEL_NAME, "input": text }, timeout=60 ) response.raise_for_status() data = response.json() embedding = data["embeddings"][0] print("向量維度:", len(embedding)) print("向量前 5 個值:", embedding[:5]) ``` 執行: ```bash python embedding_example.py ``` 可能得到類似結果: ```text 向量維度: 768 向量前 5 個值: [0.0123, -0.0456, 0.0789, ...] ``` 實際向量維度取決於所使用的 Embedding 模型。 --- ## 一次處理多筆文字 `input` 也可以傳入陣列: ```python import requests response = requests.post( "http://localhost:11434/api/embed", json={ "model": "nomic-embed-text", "input": [ "如何辦理退貨?", "退款流程需要多久?", "今天天氣很晴朗。" ] }, timeout=60 ) response.raise_for_status() data = response.json() embeddings = data["embeddings"] for index, vector in enumerate(embeddings): print(f"第 {index + 1} 筆向量維度:{len(vector)}") ``` 回傳格式大致如下: ```json { "model": "nomic-embed-text", "embeddings": [ [0.01, -0.02, 0.03], [0.04, -0.05, 0.06] ], "total_duration": 123456789 } ``` 其中: - `embeddings`:每筆文字對應一個向量 - `embeddings[0]`:第一筆文字的向量 - `embeddings[1]`:第二筆文字的向量 後續可以將這些向量存入 Chroma、FAISS、Milvus、Qdrant 或 PostgreSQL + pgvector 等向量資料庫,用於語意搜尋與 RAG。 > 注意:不同 Embedding 模型產生的向量維度與語意空間不同。建立向量資料庫後,通常應固定使用同一個模型,不能隨意混用。
相關學習地圖、教學課程
Python 人工智慧
建議完成「Python 資料工程」教程後,繼續學習以下課程。