编程AI深度实战:私有模型deep seek r1,必会ollama
系列文章:
编程AI深度实战:私有模型deep seek r1,必会ollama-CSDN博客
编程AI深度实战:自己的AI,必会LangChain-CSDN博客
编程AI深度实战:火的编程AI,都在用语法树(AST)-CSDN博客
编程AI深度实战:让verilog不再是 AI 的小众语言-CSDN博客
在您的电脑上运行 DeepSeek R1
文末r1使用指南
本教程探讨了通过 Ollama 集成和使用 DeepSeek Coder 的实际方面。我们旨在提供在本地运行 LLM 的全面指南。
这是掌握大型语言模型 (LLM) 在设备上的本地操作的良好开端。这让您可以独立支持基于 AI 的应用程序,而无需第三方 API。通过专注于在本地运行 LLM,我们还获得了隐私、控制和自定义,让开发人员和研究人员能够安全高效地充分利用这些模型的全部潜力。
了解 Ollama
在了解本地运行 LLM 的技术细节之前,了解 Ollama 是什么以及它在利用大型语言模型方面的重要性非常重要。Ollama 是一个框架,旨在简化在本地机器上部署和运行大型语言模型 (LLM)。它为开发人员和研究人员提供了一个灵活的平台,使他们能够高效地运行、自定义和管理 LLM,而无需依赖外部云服务。
通过简化设置和运行 LLM 所涉及的复杂性,Ollama 提供了更易于访问和用户友好的体验。Ollama 提供了工具和灵活性,可以在本地创新和试验 LLM,无论是出于开发、研究还是生产目的。
在此基础上,让我们探索如何通过 Ollama 集成和使用 DeepSeek Coder,直接在您的设备上利用 LLM 的强大功能。
安装 Ollama
Ollama 适用于三大操作系统:macOS、Linux 和 Windows。您可以直接从 Ollama 网站下载并安装。
首先,在您的平台上下载并安装 Ollama。
就是这样,就这么简单。
DeepSeek Coder 简介
DeepSeek Coder 是 DeepSeek 开发的一系列开源代码语言模型。DeepSeek Coder 的模型在由 87% 的代码和 13% 的自然语言组成的庞大数据集上进行训练,能够熟练理解和生成各种编程语言和任务的代码。它对 2 万亿个 token 进行训练,确保模型不仅能够熟练地生成代码,还能提供建议和优化以提高编码效率。
这是我们将在本教程中使用并在本地运行的模型。
使用 Ollama 运行 DeepSeek Coder
成功安装 Ollama 后,您可以直接在本地机器上运行 DeepSeek Coder。请注意,我并没有真正谈论硬件要求;事实是,Ollama 在没有专用硬件的情况下很好地运行了模型。我在 MacBook Pro M2 上运行它们没有任何问题。
现有型号
-
13亿参数模型:非常适合通用代码生成和小规模任务。
-
67亿参数模型:在性能和计算要求之间取得平衡,适合更复杂的代码生成任务。
-
330 亿参数模型:专为最苛刻的任务而设计,提供最高水平的性能和理解。
Ollama 基本命令
Ollama 有各种可用的 CLI 命令。从开始ollama --help查看可用的命令:
$ ollama --help
Large language model runner
Usage:
ollama [flags]
ollama [command]
Available Commands:
serve Start ollama
create Create a model from a Modelfile
show Show information for a model
run Run a model
pull Pull a model from a registry
push Push a model to a registry
list List models
cp Copy a model
rm Remove a model
help Help about any command
Flags:
-h, --help help for ollama
-v, --version Show version information
Use "ollama [command] --help" for more information about a command.
如您所见,我们有几个可用的命令。例如,您可以使用 显示模型的系统提示ollama show MODEL_NAME --system。
$ ollama show deepseek-coder --system
You are an AI programming assistant, utilizing the Deepseek Coder model,
developed by Deepseek Company,
and you only answer questions related to computer science.
For politically sensitive questions, security and privacy issues,
and other non-computer science questions, you will refuse to answer.
运行模型
Ollama 本质上允许两种与模型交互的方式:直接从 CLI 或通过公开 API 端点。第一次运行 CLI 命令时,将下载 LLM,因此可能需要一些时间;这些模型的大小出奇地小。13 亿参数的 DeepSeek Coder 模型只有大约 800 MB。
要使用 Ollama CLI 运行 DeepSeek Coder,请打开终端并根据要使用的模型大小执行以下命令之一:
-
对于13亿参数模型:
复制ollama run deepseek-coder -
对于67亿参数模型:
复制ollama run deepseek-coder:6.7b -
对于330亿参数模型:
复制ollama run deepseek-coder:33b
此命令初始化指定的 DeepSeek Coder 模型,准备生成代码或协助您的编码查询。第一次运行它时,需要更长的时间,因为它需要下载模型。
那么,让我们尝试一下:ollama run deepseek-coder在你的终端中运行它,界面就准备好了。
$ ollama run deepseek-coder
>>> Make a simple Fast API server in Python with one health check endpoint.
Here is an example of how we can implement it using the Starlette (ASGI) web framework for python that
provides us great flexibility and scalability when developing APIs, including its built-in support to
provide HTTP HEAD requests on /healthcheck endpoints which FastAPI uses by default.
This endpoint will return a simple "200 OK" response if the server is running correctly:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {
"message": "Hello World"}
@app.get("/healthcheck", status_code=200) # Specify HTTP HEAD request here as default is GET which can't
be used in the same way for health check requests
def read_root() -> dict:
return {
"status": "up"}
```
This server will respond with a message to "/" and always say that it’s up when accessed through
/healthcheck. Please note this endpoint is not available on default configuration of FastAPI as by
design, the root endpoints (like '/' or '') do NOT provide additional information about health check
requests - they are designed for system status only
我要求用 Python 制作一个简单的 Fast API 服务器,它表现良好。如果你测试代码,你会发现它有效。你也可以问后续问题:
>>> how do I run the code?
Once you've installed all necessary dependencies, here are general steps on how to start your FastAPI server and its health check endpoint
using Uvicorn.
This example assumes that `uvicorn main:app --host=0.0.0.0 --port=8001` is the command you run in terminal for development purposes, where
"main" refers back to our python file from which FastAPI app was created (in this case it's called 'run') and `--reload` will refresh your
server every time there are changes made.
You can then use curl commands like below for health checking of running app. Replace 'localhost' and ':8001' with your server hostname &
port if they are different: `curl http://localhost:8001/healthcheck -X HEAD ` (Use "-v" option to see more detailed response)
```bash
# Run this command in terminal --> For checking the health of FastAPI app. You should be able get a "2xx OK" message if server is
running correctly and it's healthy, otherwise you would expect different responses from /healthcheck endpoint or have some sort of error
logs present indicating issues with your application starting up
curl http://localhost:8001/healthcheck -X HEAD & python utils.log_handler #--> this will log health check response in the file specified
(defaults to ./logs) you can run above commands at least once and then try running FastAPI server again, it should provide more detailed
logs indicating whether app is up or not
```
In both of these cases I've used HEAD request as we need only status information without actual content. It would be different if
the endpoint requires a specific format/content type (like POST with json in above curl commands), then use `-d 'json={"key":"value"}' -H
"Content-Type: application/json"'` instead to send data or JSON payload, depending on what your health check request actually needs.
这对于简单任务和离线时无限制访问 LLM 非常有用,但现在,让我们看看如何使用它们来为其他应用程序提供支持。
通过 API 运行模型
Ollama 还支持需要以编程方式集成 DeepSeek Coder 的应用程序的 API 访问。此方法对于需要动态生成代码的 Web 应用程序或服务特别有用。
一旦模型运行,Ollama 就会公开 API http://localhost:11434,您可以使用生成API 来获取响应。
curl使用命令后,您可以在终端中执行以下操作来发出请求run:
curl -X POST http://localhost:11434/api/generate -d '{
"model": "deepseek-coder",
"prompt": "Make a simple Python script to add two numbers."
}'
您将在终端中看到该流,但由于未正确解析,因此这并不是特别有用。让我们看看如何制作一个简单的 Python 应用程序来使用此 API。
使用 Ollama 的 API 创建 Python 应用程序
这个应用程序非常简单,可以让您了解如何使用 Ollama API。创建一个新的 Python 项目,我们需要库requests,pip install requests然后粘贴以下代码:
import requests
import json
url = "http://localhost:11434/api/generate"
headers = {
'Content-Type': 'application/json',
}
conversation_history = []
while True:
print('Code with Deepseek Coder:')
user_input = input("You: ")
if user_input.lower() in ["quit", "exit"]:
print("Exiting conversation.")
break
conversation_history.append(user_input)
full_prompt = "\n".join(conversation_history)
data = {
"model": "deepseek-coder",
"stream": False,
"prompt": full_prompt,
}
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
ai_response = response_data["response"]
print("AI:", ai_response)
conversation_history.append(ai_response)
else:
print(f"Error: {response.status_code} - {response.text}")
工作原理如下:
导入必要的库
-
requests:用于向 AI 模型的 API 发送 HTTP 请求,这对于脚本和模型之间的通信至关重要。 -
json:便于以 JSON 格式编码和解码数据。该脚本使用 JSON 向 AI 模型的 API 发送数据和从其接收数据。
设置 API 通信
-
url:托管 AI 模型的 API 端点。指向模型生成函数的本地 URL 表示 AI 模型与脚本在同一台机器上运行。 -
headers:指定请求主体的内容类型为 JSON。此标头确保服务器可以正确解析请求中发送的数据。
初始化对话历史记录
conversation_history:跟踪整个对话的列表。它包括用户的提示和人工智能的回应,为人工智能模型保留上下文以生成相关回复。
交互循环
-
脚本进入无限循环,不断接受用户的输入并从 AI 模型生成响应,直到用户决定退出。
-
提示用户输入:脚本打印一条消息,邀请用户输入其消息。然后等待用户的输入。
-
退出条件:如果用户输入“quit”或“exit”,脚本会打印一条告别消息并跳出循环,结束对话。
-
更新对话历史记录:用户的输入被添加到
conversation_history列表中。 -
构建完整提示:脚本将 中的所有项目组合
conversation_history成一个字符串full_prompt,作为AI模型下一个响应的上下文。 -
准备请求的数据:发送到 AI 模型的数据包括模型的名称(
"deepseek-coder")、表示未使用流式传输的标志("stream": False)以及full_prompt作为模型的输入。 -
发送请求:脚本使用准备好的
headers和向 AI 模型的 API 发送 POST 请求data。数据采用 JSON 格式编码。 -
处理响应:
-
如果请求成功(HTTP 状态代码 200),脚本将解码 JSON 响应以提取 AI 生成的响应并打印出来。此响应也是为了
conversation_history保持对话的流畅性而添加的。 -
如果出现错误(例如,网络问题、服务器错误),脚本会打印错误状态和消息。
-
运行代码并提出一个编码问题;我这边表现良好:
$ python3 main.py
Code with Deepseek Coder:
You: make a simple python script to add two numbers
AI: Sure! Here's a very basic Python program that takes in user inputs for the first number (num1) and then second number(Num2). It adds them together using an addition operation, prints out the result.
Here is your requested code snippet :
```python
# Taking input from users/receiver of output stream by terminal or command line interface
print("Enter First Number: ") # prompt to enter first nummber
num1 = float(input()) # user's response (both numbers) are stored in variable 'a'. Typecast is necessary because we can get an input as string, so a number should be there.
# Input for the second numeric data type has to match with datatype of first numeral provided by users/receiver # prompts user enter Second Number
print("Enter The Another Nummber: ")
num2 = float(input()) # same as above, this time we are getting input from terminal or command line interface. It is stored in variable 'b' and typecast to make sure it can perform an addition operation with the numbers provided by user
# performing Addition of two inputs
sum_of = num1 + num2 # sum equals first number added second one (numbers)
print("The Sum is : ", sum_of ) # print out result. The program will output a text message saying the numbers and their sums when we run this code in python console/terminal or IDEs like PyCharm, etc
```
You can copy paste it into your Python environment where you have an active internet connection (Python Repl is recommended). If not connected to any web server then replace "input" with just a number. It will work as long both numbers are numeric in nature ie., integers or floats, etc..
这是我给我的代码;尽管输入了错误,但它运行良好!
# Taking input from users/receiver of output stream by terminal or command line interface
print("Enter First Number: ") # prompt to enter first nummber
num1 = float(input()) # user's response (both numbers) are stored in variable 'a'. Typecast is necessary because we can get an input as string, so a number should be there.
# Input for the second numeric data type has to match with datatype of first numeral provided by users/receiver # prompts user enter Second Number
print("Enter The Another Nummber: ")
num2 = float(input()) # same as above, this time we are getting input from terminal or command line interface. It is stored in variable 'b' and typecast to make sure it can perform an addition operation with the numbers provided by user
# performing Addition of two inputs
sum_of = num1 + num2 # sum equals first number added second one (numbers)
print("The Sum is : ", sum_of ) # print out result. The program will output a text message saying the numbers and their sums when we run this code in python console/terminal or IDEs like PyCharm, etc
因此,这是一种运行本地 LLM 的好方法,甚至可以使用它通过 Ollama API 为您的应用程序提供支持。在Ollama 文档中查找更多 API 。
结论
在本教程中,我们介绍了如何在本地运行大型语言模型 (LLM),利用 Ollama 框架直接在个人设备上部署和运行 DeepSeek Coder。这一探索凸显了本地 LLM 操作的显著优势,包括增强的隐私、控制以及无需依赖第三方 API 即可自定义模型以满足特定需求的能力。通过分步演示,我们展示了在主要操作系统上安装 Ollama 的简易性以及集成和运行多功能 DeepSeek Coder 的简易性,涵盖各种模型大小以适应各种任务。
实时利用语法树和AI在vim内检视代码。可以见付费文章:
编程AI深度实战:让verilog不再是 AI 的小众语言-CSDN博客
编程AI深度实战:火的编程AI,都在用语法树(AST)-CSDN博客
deepseek r1让提示词过时了
在此之前,提示词都非常重要,但是,DeepSeek R1的提示词技巧,就是没有技巧。
首先,我想明确一点的是,DeepSeek-R1是推理模型,不是通用模型。
在几个月前OpenAI o1刚刚发布时,我用通用模型的方式跟o1对话,写了一堆的结构化提示词,得到了极差的效果,那时候我一度觉得这玩意是个垃圾。
而后面,我才发现,其实是我自己的思维惯性,这玩意跟4o不一样,这不是一个很傻的聊天模型。
这是一个能力很牛逼但不知道你想要什么的真实员工。
今年1月也有一篇海外的文章很火,叫《o1 isn’t a chat model (and that’s the point)》。
跟我是完全一样的看法。
所以,有一个点一定要注意,明确你的目标,而不是给模型任务。
例如我们以前在写prompt的时候,总是会写你是一个XXX,现在我的任务是XXX,你要按照1、2、3步来给我执行balabala。
但是现在,请抛弃那些写法。

把你的一切,交给AI,让它去进行自我推理,效果会更好。AI会自动填上那些你没说出口的话,会给你想出可能更好的解决方案。
有一个不得不承认的事实是,我是一个很普通的普通人,而像我一样的很多普通人们,现在大概率是不如AI博学和聪明的。
所以,不如说出你的目标,把他当作一个很牛逼的员工,让他,放手去做。
比如这个case。

只需要表达你是谁+你的目标就OK。
特别是你是谁这个背景信息,非常非常的有用。

所以请抛弃掉一起过往所学习的结构化框架,如果真的需要有一个万能Prompt模板,那就是:
- 你是谁 + 背景信息 + 你的目标
背景信息给的越多越能让R1理解你的需求帮助你更好的完成任务。
时刻把他当成:
这是一个能力很牛逼但不知道你想要什么的员工。
最牛逼的提示词技巧,就是没有技巧。
大道至简,重剑无锋。
所以,千言万语汇聚成一句话就是:用人话清晰的表达出你的需求,这就够了。
更多推荐



所有评论(0)