Ollama本地部署

下载安装ollama

https://ollama.com/download,windows版本国内网络下载慢可以用迅雷下载比较快

查看有哪些model可供下载

https://ollama.com/library

安装什么model

模型名称参数大小推荐内存速度能力特点适用场景
qwen2.5:0.5b 0.5B < 1GB ⭐⭐⭐⭐⭐ ⭐⭐☆ 中文特化,速度极致 纯中文快速对话
llama3.2:1b 1B ~1GB ⭐⭐⭐⭐⭐ ⭐⭐⭐ 综合最佳,生态好 通用入门首选
gemma2:2b 2B ~2GB ⭐⭐⭐⭐ ⭐⭐⭐ 均衡,安全 均衡任务
llama3.2:3b 3B ~3GB ⭐⭐⭐⭐ ⭐⭐⭐☆ 能力增强版 需要更强能力
phi3:mini 3.8B ~4GB ⭐⭐⭐⭐ ⭐⭐⭐⭐ 小钢炮,强推理 轻量编码和推理

  1. 第一次尝试,无脑选:ollama run llama3.2:1b

  2. 主要用中文,追求极致速度:ollama run qwen2.5:0.5b

  3. 感觉小模型有点弱,想试试强一点的:ollama run phi3:mini 或 ollama run llama3.2:3b

安装model

方法1.如图,选择model后随便提个问题,就会自动下载选择的model

image

 方法2:ollama pull model, 如ollama pull llama2

查看已安装的model

C:\Users\xxx>ollama list
NAME ID SIZE MODIFIED
llama2:latest 78e26419b446 3.8 GB About a minute ago
gpt-oss:20b aa4295ac10c3 13 GB 24 minutes ago

现在就可以在ollama UI窗口提问题了

ollama要求

  • CPU:多核处理器(推荐 4 核或以上)。
  • GPU:如果你计划运行大型模型或进行微调,推荐使用具有较高计算能力的 GPU(如 NVIDIA 的 CUDA 支持)。
  • 内存:至少 8GB RAM,运行较大模型时推荐 16GB 或更高。
  • 存储:需要足够的硬盘空间来存储预训练模型,通常需要 10GB 至数百 GB 的空间,具体取决于模型的大小。
  • 软件要求:确保系统上安装了最新版本的 Python(如果打算使用 Python SDK)。

我的电脑配置不够,所以一个问题得等5分钟才能答完

 python ollama

pip install ollama
#一次性相响应
import ollama
response = ollama.generate(
model="qwen2.5:0.5b", # 模型名称
prompt="JS怎么发起get post put delete请求", # 提示文本
stream=False
)
print(response)
"""

model='qwen2.5:0.5b' created_at='2025-08-30T14:33:53.9313696Z' done=True done_reason='stop' total_duration=21634910800 load_duration=91260900 prompt_eval_count=37 prompt_eval_duration=30577100 eval_count=580 eval_duration=21511551900 response="在JavaScript中,我们可以使用`XMLHttpRequest`或者Promise来发起不同类型的HTTP GET、POST、PUT和DELETE请求。以下是一些示例:\n\n1. **POST请求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('POST', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n ```\n - 使用Promise(浏览器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('POST', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n2. **GET请求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('GET', 'https://example.com/api/data');\n xhr.send();\n ```\n - 使用Promise(浏览器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('GET', 'https://example.com/api/data');\n xhr.send();\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n3. **PUT请求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('PUT', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n ```\n - 使用Promise(浏览器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('PUT', 'https://example.com/api/data');\n xhr.setRequestHeader('Content-Type', 'application/json');\n xhr.send(JSON.stringify({ key: 'value' }));\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n4. **DELETE请求**:\n - 使用`XMLHttpRequest`:\n ```javascript\n var xhr = new XMLHttpRequest();\n xhr.open('DELETE', 'https://example.com/api/data');\n ```\n - 使用Promise(浏览器):\n ```javascript\n const promise = new Promise((resolve, reject) => {\n xhr.open('DELETE', 'https://example.com/api/data');\n xhr.send();\n });\n promise.then(data => console.log(data));\n promise.catch(reject);\n ```\n\n在每个请求中,我们都可以明确地指定目标URL、方法(POST、PUT、DELETE)、以及包含的参数。请根据需要调整URL和数据格式以适应具体需求。]


"""
#流式响应
import ollama response = ollama.generate( model="qwen2.5:0.5b", # 模型名称 prompt="JS怎么发起get post put delete请求", # 提示文本 stream=True ) print(response) full_response = "" for chunk in response: # 每次获取一个片段,并打印出来(实现打字机效果) part = chunk.get('response', '') print(part, end='', flush=True) # end='' 确保不换行 full_response += part # 打印一个换行,然后你可以使用完整的 full_response 变量 print("\n\n---完整回答已生成---")
"""

<generator object Client._request.<locals>.inner at 0x000002244C232440>
在JavaScript中,我们可以使用`fetch()` API来发送HTTP请求。以下是一些常见的GET、POST、PUT和DELETE请求的例子:

1. GET 请求:
```javascript
fetch('https://example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
```

2. POST 请求:
```javascript
fetch('https://example.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Hello, World!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```

3. PUT 请求:
```javascript
fetch('https://example.com', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Updated data!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```

4. DELETE 请求:
```javascript
fetch('https://example.com', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ data: 'Delete data!' })
})
.then(response => response.json())
.catch(error => console.error(error));
```

5. 其他请求方法:
- GET 请求:与`fetch('https://example.com')`相同。
- POST 请求:与`fetch('https://example.com', { method: 'POST' })`相同。
- PUT 请求:与`fetch('https://example.com', { method: 'PUT' })`相同。
- DELETE 请求:与`fetch('https://example.com', { method: 'DELETE')}`相同。

每个请求都会以JSON格式返回响应。如果你需要发送不同的数据,可以在请求头中添加适当的字段(例如,用`Content-Type`设置为`application/json`),并且在发送请求时传递相应的参数或实体数据。

---完整回答已生成---


"""
#流式响应
from ollama import Client
client = Client(host='http://localhost:11434')
# 使用 chat 接口
response = client.chat(
    model='qwen2.5:0.5b',
    messages=[
        {
            'role': 'user',
            'content': 'JS怎么发起get post put delete请求',
        },
    ],
    stream=True
)
full_response = ""
for chunk in response:
    # 从 chunk 中获取消息内容
    content = chunk['message']['content']
    print(content, end='', flush=True)
    full_response += content

print("\n\n---完整回答已生成---")



#流式响应
from ollama import chat
stream = chat(
model='deepseek-coder',
messages=[{'role': 'user', 'content': 'JS网格布局'}],
stream=True,
)
# 逐块打印响应内容
for chunk in stream:
print(chunk['message']['content'], end='', flush=True)

  

ollama命令

ollama serve #启动 Ollama 服务以在后台运行
ollama stop  #停止正在运行的 Ollama 服务
ollama restart #重启 Ollama 服务
ollama version #查看当前安装的 Ollama 版本
ollama update #更新 Ollama 到最新版本
ollama clean    #清理 Ollama 的缓存
ollama show <model-name>#查看指定模型的详细信息
ollama deps <model-name> #查看模型的依赖关系
ollama config <model-name> #查看模型的配置文件
ollama export <model-name> <output-file> #将模型导出为文件
ollama import <input-file> #从文件导入模型
ollama system #查看 Ollama 的系统信息
ollama resources <model-name> #查看模型的资源使用情况
ollama perf <model-name> #查看模型的性能指标
ollama history <model-name> #查看模型的历史记录
ollama status <model-name> #检查指定模型的状态
ollama logs  #查看 Ollama 的日志信息
ollama pull <model-name> #拉取模型
ollama run <model-name>  #运行模型
ollama list                            #列出本地模型
ollama rm <model-name>   #删除模型
ollama create <custom-model-name> -f <Modelfile> #基于现有模型创建自定义模型
ollama cp <source-model-name> <new-model-name> #复制一个已存在的模型
ollama push <model-name>#推送自定义模型

  

ollama模型交互

>ollama run qwen2.5:0.5b #交互式运行模型
>>> who are you
I am Qwen, a large language model developed by Alibaba Cloud to help with various tasks such as summarizing text
and generating human-like responses. If you have any questions or need assistance with something specific, feel
free to ask!

>>> pyqt
PyQt is a comprehensive library for creating desktop applications in Python. It provides extensive support for GUI
programming, allowing developers to create richly interactive user interfaces, including widgets and graphical
components that interact with the mouse and keyboard.

Key features of PyQt include:

1. User interface creation: It supports various widget types such as buttons, sliders, lists, etc., which are
commonly used in desktop applications.
2. Data handling: It is designed for data manipulation tasks such as filtering, searching, sorting, and plotting
data.
3. Animation support: PyQt provides features like frames and animations to create interactive applications.
4. Event-driven programming: It supports event-based programming, allowing developers to control the state of GUI
elements directly.
5. Cross-platform compatibility: PyQt can be run on Windows, macOS, and Linux.

PyQt is widely used in various fields such as mobile app development, web applications, scientific computing, and
more. It provides a wide range of tools and features that make it an essential tool for creating dynamic user
interfaces.

If you have any specific questions about PyQt or need help with implementing certain functionalities in your
application, feel free to ask!

>>> /bye #退出模型

ollama run qwen2.5:0.5b "pyqt"#命令行参数运行
echo "pyqt" | ollama run llama2:latest #使用管道运行模型

ollama API 交互

1. 启动 Ollama 服务
在使用 API 之前,需要确保 Ollama 服务正在运行。可以通过以下命令启动服务:

ollama serve
默认情况下,服务会运行在 http://localhost:11434。#所以你再次运行会报错Error: listen tcp 127.0.0.1:11434: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted.

2. API 端点
Ollama 提供了以下主要 API 端点:

生成文本(Generate Text)
端点:POST /api/generate

功能:向模型发送提示词(prompt),并获取生成的文本。

请求格式:

{
  "model": "<model-name>",  // 模型名称
  "prompt": "<input-text>", // 输入的提示词
  "stream": false,          // 是否启用流式响应(默认 false)
  "options": {              // 可选参数
    "temperature": 0.7,     // 温度参数
    "max_tokens": 100       // 最大 token 数
  }
}
响应格式:

{
  "response": "<generated-text>", // 生成的文本
  "done": true                    // 是否完成
}
聊天(Chat)
端点:POST /api/chat

功能:支持多轮对话,模型会记住上下文。

请求格式:

{
  "model": "<model-name>",  // 模型名称
  "messages": [             // 消息列表
    {
      "role": "user",       // 用户角色
      "content": "<input-text>" // 用户输入
    }
  ],
  "stream": false,          // 是否启用流式响应
  "options": {              // 可选参数
    "temperature": 0.7,
    "max_tokens": 100
  }
}
响应格式:

{
  "message": {
    "role": "assistant",    // 助手角色
    "content": "<generated-text>" // 生成的文本
  },
  "done": true
}
列出本地模型(List Models)
端点:GET /api/tags

功能:列出本地已下载的模型。

响应格式:

{
  "models": [
    {
      "name": "<model-name>", // 模型名称
      "size": "<model-size>", // 模型大小
      "modified_at": "<timestamp>" // 修改时间
    }
  ]
}
拉取模型(Pull Model)
端点:POST /api/pull

功能:从模型库中拉取模型。

请求格式:

{
  "name": "<model-name>" // 模型名称
}
响应格式:

{
  "status": "downloading", // 下载状态
  "digest": "<model-digest>" // 模型摘要
}
3. 使用示例
生成文本
使用 curl 发送请求:

实例
curl http://localhost:11434/api/generate -d '{
  "model": "deepseek-coder",
  "prompt": "你好,你能帮我写一段代码吗?",
  "stream": false
}'
多轮对话
使用 curl 发送请求:

实例
curl http://localhost:11434/api/chat -d '{
  "model": "deepseek-coder",
  "messages": [
    {
      "role": "user",
      "content": "你好,你能帮我写一段 Python 代码吗?"
    }
  ],
  "stream": false
}'
列出本地模型
使用 curl 发送请求:

curl http://localhost:11434/api/tags
拉取模型
使用 curl 发送请求:

实例
curl http://localhost:11434/api/pull -d '{
  "name": "deepseek-coder"
}'
4. 流式响应
Ollama 支持流式响应(streaming response),适用于实时生成文本的场景。

启用流式响应
在请求中设置 "stream": true,API 会逐行返回生成的文本。

实例
curl http://localhost:11434/api/generate -d '{
  "model": "deepseek-coder",
  "prompt": "你好,你能帮我写一段代码吗?",
  "stream": true
}'
响应格式
每行返回一个 JSON 对象:

实例
{
  "response": "<partial-text>", // 部分生成的文本
  "done": false                 // 是否完成
}
5. 编程语言示例
Python 使用 requests 库与 Ollama API 交互:

实例
import requests

# 生成文本
response = requests.post(
    "http://localhost:11434/api/generate",
    json={
        "model": "deepseek-coder",
        "prompt": "你好,你能帮我写一段代码吗?",
        "stream": False
    }
)
print(response.json())
多轮对话:

实例
response = requests.post(
    "http://localhost:11434/api/chat",
    json={
        "model": "deepseek-coder",
        "messages": [
            {
                "role": "user",
                "content": "你好,你能帮我写一段 Python 代码吗?"
            }
        ],
        "stream": False
    }
)
print(response.json())
JavaScript 使用 fetch API 与 Ollama 交互:

实例
// 生成文本
fetch("http://localhost:11434/api/generate", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "deepseek-coder",
    prompt: "你好,你能帮我写一段代码吗?",
    stream: false
  })
})
  .then(response => response.json())
  .then(data => console.log(data));
多轮对话:

实例
fetch("http://localhost:11434/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "deepseek-coder",
    messages: [
      {
        role: "user",
        content: "你好,你能帮我写一段 Python 代码吗?"
      }
    ],
    stream: false
  })
})
  .then(response => response.json())
  .then(data => console.log(data));

 

posted @ 2025-08-30 20:24  我的腹肌不见了  阅读(4)  评论(0)    收藏  举报