阿川私房教材:
學 JavaScript 前端,帶作品集去面試!

63 個專案實戰,寫出作品集,讓面試官眼前一亮!

立即開始免費試讀!

DeepSeek-R1 在人工智慧界引起了不小的轟動。該模型由中國人工智慧公司DeepSeek開發,正在與 OpenAI 的頂級模型進行比較。 DeepSeek-R1 之所以令人興奮,不僅是因為它的功能,還因為它是開源的,任何人都可以下載並在本地執行它。在這篇部落格中,我將指導您使用 Ollama 在您的機器上設定 DeepSeek-R1。

為什麼選擇 DeepSeek-R1?

DeepSeek R1

DeepSeek-R1 脫穎而出有幾個原因。它不僅比許多其他模型便宜,而且在解決問題、推理和編碼方面表現出色。其內建的思維鏈推理提高了其效率,使其成為其他模型的有力競爭者。讓我們深入了解如何在本機系統上執行該模型。

開始使用 Ollama

奧拉馬徽標

在我們開始之前,讓我們討論一下 Ollama。 Ollama 是一款免費的開源工具,可讓使用者在本地執行自然語言處理模型。使用 Ollama,您可以輕鬆下載並執行 DeepSeek-R1 模型。

你可以按照以下方式開始:

步驟1:安裝Ollama

首先,您需要下載並安裝Ollama 。造訪 Ollama 網站並下載與您的作業系統相符的版本。

請按照網站上提供的安裝說明進行操作。

安裝 ollama

第 2 步:下載 DeepSeek-R1

步驟 2 下載 deepseek-R1

正如你所看到的,當你造訪 Ollama 網站時,你可以執行 DeepSeek-R1 的不同參數。您可以在此處找到要求的詳細資訊(如上圖所示)

您可以執行 1.5b、7b、8b、14b、32b、70b、671b,顯然隨著您選擇更大的參數,硬體需求也會增加。我在我的教程中使用了 7b。

安裝 Ollama 後,打開終端機並輸入以下命令下載 DeepSeek-R1 模型:

DeepSeek-7b

ollama run deepseek-r1

此命令告訴 Ollama 下載模型。根據您的網速,這可能需要一些時間。完成時喝杯咖啡!

步驟 3:驗證安裝

下載後,執行以下命令以驗證安裝:

ollama list

您應該在可用模型清單中看到 deepseek-r1。如果你做到了,那就太好了!您已準備好執行模型。

步驟 4:執行 DeepSeek-R1

現在,讓我們使用以下命令啟動模型:

ollama run deepseek-r1

就這樣,您就可以在本地與 DeepSeek-R1 互動。就這麼簡單!

第 5 步:提出疑問

提出疑問

透過模型進行思路鏈推理。

思路

該模型在編碼任務中表現也很好。我們也來檢查一下這種方法。

deepseek 程式碼生成

上述程式碼相關查詢的詳細答案。

程式碼生成 R1

以下是使用 DeepSeek-R1 處理不同用例的完整逐步影片。

https://youtu.be/8g93GmueeWs

我對 DeepSeek-R1 的第一印象簡直令人震驚:)

按照本指南,您已成功使用 Ollama 在本機上設定 DeepSeek-R1。此設定為 AI 整合提供了強大的解決方案,為您的應用程式提供隱私、速度和控制。享受使用 DeepSeek-R1 進行實驗並探索本地 AI 模型的潛力。順便說一句,為您的 AI/ML 應用程式擁有一個強大的資料庫是必須的。我建議使用像SingleStore這樣的一體化資料平台。


使用 DeepSeek 和 SingleStore 的 RAG 應用程式

如果您想擴展學習並建立一個簡單的 RAG 應用程式,您可以按照本教程進行操作。我們將在這裡使用SingleStore作為向量資料庫來儲存我們的資料。 Singlestore 是一個用於建立 AI/ML 應用程式的一體化資料平台。

1. 先決條件

所需的庫:

pip install singlestoredb sentence-transformers deepseek-sdk python-dotenv

設定環境

建立.env檔:

SINGLESTORE_HOST=your-singlestore-host
SINGLESTORE_USER=your-username
SINGLESTORE_PASSWORD=your-password
DEEPSEEK_API_KEY=your-api-key

從 SingleStore Cloud 和 DeepSeek API 取得憑證。

資料庫設定

在 SingleStore 中建立一個新的資料庫:

CREATE DATABASE rag_db;

該程式碼將自動建立文件表

文件準備

用您自己的資料取代範例文件列表

  • 對於大型資料集,請考慮批次處理

執行應用程式

python rag_app.py

範例用法

# Custom query example
query = "How does SingleStore handle vector search?"
print(rag.generate_response(query))

完整程式碼更新如下,

import os
import numpy as np
from typing import List
import singlestoredb as s2
from getpass import getpass
from sentence_transformers import SentenceTransformer
from deepseek_sdk import DeepSeek

class RAGApplication:
    def __init__(self):
        self._load_env()
        self._init_db()
        self._init_models()

    def _load_env(self):
        self.db_config = {
            'host': os.getenv('SINGLESTORE_HOST', 'localhost'),
            'port': 3306,
            'user': os.getenv('SINGLESTORE_USER', 'root'),
            'password': os.getenv('SINGLESTORE_PASSWORD', ''),
            'database': os.getenv('SINGLESTORE_DB', 'rag_db')
        }
        self.deepseek_key = os.getenv('DEEPSEEK_API_KEY') or getpass('DeepSeek API key: ')

    def _init_db(self):
        # Create connection pool
        self.pool = s2.create_pool(**self.db_config)
        self._create_table()

    def _create_table(self):
        create_table_sql = """
        CREATE TABLE IF NOT EXISTS documents (
            id INT PRIMARY KEY AUTO_INCREMENT,
            text TEXT,
            embedding BLOB,
            VECTOR INDEX (embedding) USING FLAT
        )
        """
        with self.pool.connect() as conn:
            conn.execute(create_table_sql)

    def _init_models(self):
        self.embedder = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
        self.llm = DeepSeek(api_key=self.deepseek_key)

    def store_documents(self, documents: List[str]):
        embeddings = self.embedder.encode(documents)

        insert_sql = """
        INSERT INTO documents (text, embedding)
        VALUES (%s, JSON_ARRAY_PACK(%s))
        """

        with self.pool.connect() as conn:
            with conn.cursor() as cursor:
                cursor.executemany(insert_sql, [
                    (text, f'[{",".join(map(str, emb.tolist()))}]')
                    for text, emb in zip(documents, embeddings)
                ])
            conn.commit()

    def retrieve_context(self, query: str, top_k: int = 3) -> List[str]:
        query_embedding = self.embedder.encode([query])[0].tolist()

        search_sql = """
        SELECT text
        FROM documents
        ORDER BY DOT_PRODUCT(embedding, JSON_ARRAY_PACK(%s)) DESC
        LIMIT %s
        """

        with self.pool.connect() as conn:
            with conn.cursor() as cursor:
                cursor.execute(search_sql, (
                    f'[{",".join(map(str, query_embedding))}]',
                    top_k
                ))
                results = cursor.fetchall()

        return [result[0] for result in results]

    def generate_response(self, query: str) -> str:
        context = self.retrieve_context(query)
        prompt = f"Context:\n{'\n'.join(context)}\n\nQuestion: {query}\nAnswer:"

        response = self.llm.chat(
            messages=[{'role': 'user', 'content': prompt}],
            temperature=0.7
        )

        return response.choices[0].message.content

if __name__ == "__main__":
    rag = RAGApplication()

    # Store sample documents
    documents = [
        "DeepSeek is a Chinese AI company focused on AGI research.",
        "SingleStore is a distributed SQL database optimized for real-time analytics.",
        "RAG combines retrieval from databases with LLM generation.",
        "Vector embeddings represent text as numerical vectors for similarity search."
    ]
    rag.store_documents(documents)

    # Example query
    query = "What is RAG?"
    print(rag.generate_response(query))

感謝您閱讀我的文章。您也可以透過我的Youtube 頻道關注我。我每週都會製作與 AI/ML/Data 相關的影片。


原文出處:https://dev.to/pavanbelagatti/run-deepseek-r1-locally-for-free-in-just-3-minutes-1e82


共有 0 則留言


精選技術文章翻譯,幫助開發者持續吸收新知。

阿川私房教材:
學 JavaScript 前端,帶作品集去面試!

63 個專案實戰,寫出作品集,讓面試官眼前一亮!

立即開始免費試讀!