ollama搭建本地ai大模型并应用调用

1、下载ollama
1)https://ollama.com 进入网址,点击download下载
2)下载后直接安装即可。
2、启动配置模型
默认是启动cmd窗口直接输入
1 ollama run llama3
启动llama3大模型 或者启动千问大模型
1 ollama run qwen2
启动输入你需要输入的问题即可

3、配置UI界面
安装docker
并部署web操作界面
1 docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui --restart always ghcr.io/open-webui/open-webui:main
安装完毕后,安装包较大,需等待一段时间。
localhost:3000即可打开网址

4、搭建本地知识库
AnythingLLM
5、配置文件
开发11434端口,便于外部访问接口,如果跨域访问的话配置OLLAMA_ORIGINS=*
Windows版
只需要在系统环境变量中直接配置,
OLLAMA_HOST为变量名,"0.0.0.0:11434"为变量值
1 OLLAMA_HOST= "0.0.0.0:11434"
MAC版
配置OLLAMA_HOST
1 sudo sh -c 'echo "export OLLAMA_HOST=0.0.0.0:11434">>/etc/profile'launchctl setenv OLLAMA_HOST "0.0.0.0:11434"
Linux版
配置OLLAMA_HOST
1 Environment="OLLAMA\_HOST=0.0.0.0"
6、程序调用接口
golang实现例子:流式响应速度更快,用户体验更佳。
golang例子:非流式响应
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
)
const (
obaseURL = "http://localhost:11434/api"
omodelID = "qwen2:0.5b" // 选择合适的模型
oendpoint = "/chat" //"/chat/completions"
)
// ChatCompletionRequest 定义了请求体的结构
type olChatCompletionRequest struct {
Model string `json:"model"`
Messages []struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"messages"`
Stream bool `json:"stream"`
//Temperature float32 `json:"temperature"`
}
// ChatCompletionResponse 定义了响应体的结构
type olChatCompletionResponse struct {
//Choices []struct {
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
//} `json:"choices"`
}
// sendRequestWithRetry 发送请求并处理可能的429错误
func olsendRequestWithRetry(client *http.Client, requestBody []byte) (*http.Response, error) {
req, err := http.NewRequest("POST", obaseURL+oendpoint, bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
//req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == http.StatusTooManyRequests {
retryAfter := resp.Header.Get("Retry-After")
if retryAfter != "" {
duration, _ := time.ParseDuration(retryAfter)
time.Sleep(duration)
} else {
time.Sleep(5 * time.Second) // 默认等待5秒
}
return olsendRequestWithRetry(client, requestBody) // 递归重试
}
return resp, nil
}
func main() {
client := &http.Client{} // 创建一个全局的 HTTP 客户端实例
// 初始化对话历史记录
history := []struct {
Role string `json:"role"`
Content string `json:"content"`
}{
{"system", "你是一位唐代诗人,特别擅长模仿李白的风格。"},
}
// 创建标准输入的扫描器
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("请输入您的问题(或者输入 'exit' 退出): ")
scanner.Scan()
userInput := strings.TrimSpace(scanner.Text())
// 退出条件
if userInput == "exit" {
fmt.Println("感谢使用,再见!")
break
}
// 添加用户输入到历史记录
history = append(history, struct {
Role string `json:"role"`
Content string `json:"content"`
}{
"user",
userInput,
})
// 创建请求体
requestBody := olChatCompletionRequest{
Model: omodelID,
Messages: history,
Stream: false,
//Temperature: 0.7,
}
// 构建完整的请求体,包含历史消息
requestBody.Messages = append([]struct {
Role string `json:"role"`
Content string `json:"content"`
}{
{
Role: "system",
Content: "你是一位唐代诗人,特别擅长模仿李白的风格。",
},
}, history...)
// 将请求体序列化为 JSON
requestBodyJSON, err := json.Marshal(requestBody)
if err != nil {
fmt.Println("Error marshalling request body:", err)
continue
}
fmt.Println("wocao:" + string(requestBodyJSON))
// 发送请求并处理重试
resp, err := olsendRequestWithRetry(client, requestBodyJSON)
if err != nil {
fmt.Println("Error sending request after retries:", err)
continue
}
defer resp.Body.Close()
// 检查响应状态码
if resp.StatusCode != http.StatusOK {
fmt.Printf("Received non-200 response status code: %d\n", resp.StatusCode)
continue
}
// 读取响应体
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
continue
}
//fmt.Println("0000" + string(responseBody))
// 解析响应体
var completionResponse olChatCompletionResponse
err = json.Unmarshal(responseBody, &completionResponse)
if err != nil {
fmt.Println("Error unmarshalling response body:", err)
continue
}
fmt.Printf("AI 回复: %s\n", completionResponse.Message.Content) // choice.Message.Content
// 将用户的消息添加到历史记录中
history = append(history, struct {
Role string `json:"role"`
Content string `json:"content"`
}{
Role: completionResponse.Message.Role,
Content: completionResponse.Message.Content, // 假设用户的消息是第一个
})
}
}
golang例子:流式响应
1 package main
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/json"
7 "fmt"
8 "io"
9 "net/http"
10 "os"
11 "strings"
12 "time"
13 )
14
15 const (
16 obaseURL = "http://localhost:11434/api"
17 omodelID = "qwen2:0.5b" // 选择合适的模型
18 oendpoint = "/chat" //"/chat/completions"
19 )
20
21 // ChatCompletionRequest 定义了请求体的结构
22 type olChatCompletionRequest struct {
23 Model string `json:"model"`
24 Messages []struct {
25 Role string `json:"role"`
26 Content string `json:"content"`
27 } `json:"messages"`
28 Stream bool `json:"stream"`
29 //Temperature float32 `json:"temperature"`
30 }
31
32 // ChatCompletionResponse 定义了响应体的结构
33 type olChatCompletionResponse struct {
34 //Choices []struct {
35 Message struct {
36 Role string `json:"role"`
37 Content string `json:"content"`
38 } `json:"message"`
39 //} `json:"choices"`
40 }
41
42 // sendRequestWithRetry 发送请求并处理可能的429错误
43 func olsendRequestWithRetry(client *http.Client, requestBody []byte) (*http.Response, error) {
44 req, err := http.NewRequest("POST", obaseURL+oendpoint, bytes.NewBuffer(requestBody))
45 if err != nil {
46 return nil, err
47 }
48
49 req.Header.Set("Content-Type", "application/json")
50 //req.Header.Set("Authorization", "Bearer "+apiKey)
51
52 resp, err := client.Do(req)
53 if err != nil {
54 return nil, err
55 }
56
57 if resp.StatusCode == http.StatusTooManyRequests {
58 retryAfter := resp.Header.Get("Retry-After")
59 if retryAfter != "" {
60 duration, _ := time.ParseDuration(retryAfter)
61 time.Sleep(duration)
62 } else {
63 time.Sleep(5 * time.Second) // 默认等待5秒
64 }
65 return olsendRequestWithRetry(client, requestBody) // 递归重试
66 }
67
68 return resp, nil
69 }
70
71 func main() {
72 client := &http.Client{} // 创建一个全局的 HTTP 客户端实例
73
74 // 初始化对话历史记录
75 history := []struct {
76 Role string `json:"role"`
77 Content string `json:"content"`
78 }{
79 {"system", "你是一位唐代诗人,特别擅长模仿李白的风格。"},
80 }
81
82 // 创建标准输入的扫描器
83 scanner := bufio.NewScanner(os.Stdin)
84
85 for {
86 fmt.Print("请输入您的问题(或者输入 'exit' 退出): ")
87 scanner.Scan()
88 userInput := strings.TrimSpace(scanner.Text())
89
90 // 退出条件
91 if userInput == "exit" {
92 fmt.Println("感谢使用,再见!")
93 break
94 }
95
96 // 添加用户输入到历史记录
97 history = append(history, struct {
98 Role string `json:"role"`
99 Content string `json:"content"`
100 }{
101 "user",
102 userInput,
103 })
104
105 // 创建请求体
106 requestBody := olChatCompletionRequest{
107 Model: omodelID,
108 Messages: history,
109 Stream: true,
110 //Temperature: 0.7,
111 }
112
113 // 构建完整的请求体,包含历史消息
114 requestBody.Messages = append([]struct {
115 Role string `json:"role"`
116 Content string `json:"content"`
117 }{
118 {
119 Role: "system",
120 Content: "你是一位唐代诗人,特别擅长模仿李白的风格。",
121 },
122 }, history...)
123
124 // 将请求体序列化为 JSON
125 requestBodyJSON, err := json.Marshal(requestBody)
126 if err != nil {
127 fmt.Println("Error marshalling request body:", err)
128 continue
129 }
130 fmt.Println("wocao:" + string(requestBodyJSON))
131 // 发送请求并处理重试
132 resp, err := olsendRequestWithRetry(client, requestBodyJSON)
133 if err != nil {
134 fmt.Println("Error sending request after retries:", err)
135 continue
136 }
137 defer resp.Body.Close()
138
139 // 检查响应状态码
140 if resp.StatusCode != http.StatusOK {
141 fmt.Printf("Received non-200 response status code: %d\n", resp.StatusCode)
142 continue
143 }
144 resutlmessage := ""
145 streamReader := resp.Body
146 buf := make([]byte, 1024) // 或者使用更大的缓冲区来提高读取性能
147 var completionResponse olChatCompletionResponse
148 fmt.Print("AI 回复:")
149 for {
150 n, err := streamReader.Read(buf)
151 if n > 0 {
152 // 处理接收到的数据,这里简单打印出来
153 //fmt.Print(string(buf[:n]))
154 err = json.Unmarshal(buf[:n], &completionResponse)
155 fmt.Print(string(completionResponse.Message.Content))
156 resutlmessage+=string(completionResponse.Message.Content)
157 if err != nil {
158 fmt.Println("Error unmarshalling response body:", err)
159 continue
160 }
161 }
162 if err != nil {
163 if err == io.EOF {
164 fmt.Println("")
165 break
166 }
167 panic(err)
168 }
169 }
170
171 // 将用户的消息添加到历史记录中
172 history = append(history, struct {
173 Role string `json:"role"`
174 Content string `json:"content"`
175 }{
176 Role: completionResponse.Message.Role,
177 Content: resutlmessage,//completionResponse.Message.Content, // 假设用户的消息是第一个
178 })
179 }
180 }
感谢观看,谢谢!
ollama搭建本地ai大模型并应用调用的更多相关文章
- AI大模型学习了解
# 百度文心 上线时间:2019年3月 官方介绍:https://wenxin.baidu.com/ 发布地点: 参考资料: 2600亿!全球最大中文单体模型鹏城-百度·文心发布 # 华为盘古 上线时 ...
- 华为高级研究员谢凌曦:下一代AI将走向何方?盘古大模型探路之旅
摘要:为了更深入理解千亿参数的盘古大模型,华为云社区采访到了华为云EI盘古团队高级研究员谢凌曦.谢博士以非常通俗的方式为我们娓娓道来了盘古大模型研发的"前世今生",以及它背后的艰难 ...
- 保姆级教程:用GPU云主机搭建AI大语言模型并用Flask封装成API,实现用户与模型对话
导读 在当今的人工智能时代,大型AI模型已成为获得人工智能应用程序的关键.但是,这些巨大的模型需要庞大的计算资源和存储空间,因此搭建这些模型并对它们进行交互需要强大的计算能力,这通常需要使用云计算服务 ...
- Dnsmasq安装与配置-搭建本地DNS服务器 更干净更快无广告DNS解析
默认的情况下,我们平时上网用的本地DNS服务器都是使用电信或者联通的,但是这样也导致了不少的问题,首当其冲的就是上网时经常莫名地弹出广告,或者莫名的流量被消耗掉导致网速变慢.其次是部分网站域名不能正常 ...
- 【转】使用Apache Kylin搭建企业级开源大数据分析平台
http://www.thebigdata.cn/JieJueFangAn/30143.html 本篇文章整理自史少锋4月23日在『1024大数据技术峰会』上的分享实录:使用Apache Kylin搭 ...
- IIS搭建本地服务器,花生壳实现外网通过域名访问网站
配置服务器 作为一个青年,没有实力,做不出标图所示的服务器. 作为一个学生,买不起服务器 作为一个小孩,买不起域名 但别忘了 作为一个平民玩家,只要有耐心 装备迟早会做出来的 (注:感觉有钱与没钱还是 ...
- centos 如何用 rsyslog 搭建本地日志服务(续1: omprog模块与php deamon的配合使用)
上一篇说到了如何用 rsyslog 搭建本地的日志服务,地址在这里,没有看的童鞋可以先瞅一眼 : http://www.cnblogs.com/smallrookie/p/5677004.html 显 ...
- spring boot / cloud (十八) 使用docker快速搭建本地环境
spring boot / cloud (十八) 使用docker快速搭建本地环境 在平时的开发中工作中,环境的搭建其实一直都是一个很麻烦的事情 特别是现在,系统越来越复杂,所需要连接的一些中间件也越 ...
- EF框架搭建小总结--CodeFirst模型优先
前言:之前在下总结编写了一篇 EF框架搭建小总结--ModelFirst模型优先 博文,看到一段时间内该博文的访问量蹭.蹭蹭.蹭蹭蹭...往上涨(实际也不是很多,嘿嘿),但是还是按捺不住内心的喜悦(蛮 ...
- HBase实践案例:知乎 AI 用户模型服务性能优化实践
用户模型简介 知乎 AI 用户模型服务于知乎两亿多用户,主要为首页.推荐.广告.知识服务.想法.关注页等业务场景提供数据和服务, 例如首页个性化 Feed 的召回和排序.相关回答等用到的用户长期兴趣特 ...
随机推荐
- C++判断字符串是否相等
话不多说,上代码 bool str_same(char *p1, char *p2) { if (strcmp(p1, p2)) return 0; else for (int i = 0; i &l ...
- Python图像暗水印添加
推荐使用库: blind-watermark pip install blind-watermark https://github.com/guofei9987/blind_watermark
- python基础-集合set { }
集合的定义和操作 集合的特性: 元素数量 支持多个 元素类型 任意 下标索引 支持 重复元素 不支持 可修改性 支持 数据有序 否 使用场景 不可重复的数据记录场景 # 定义集合 my_set = { ...
- 全志T3+FPGA国产核心板——Pango Design Suite的FPGA程序加载固化
本文主要基于紫光同创Pango Design Suite(PDS)开发软件,演示FPGA程序的加载.固化,以及程序编译等方法.适用的开发环境为Windows 7/10 64bit. 测试板卡为全志T3 ...
- 2024年,AI驱动测试管理工具会有哪些发展前景呢?
随着人工智能技术的日新月异,2024年的测试管理工具将迎来全新的发展机遇.AI赋能将助力测试管理工具实现前所未有的智能化升级,为软件研发团队带来革命性的变革. 一.什么是AI? 人工智能(AI)是一种 ...
- SpringBoot配置Mysql连接池
一.HikariCP连接池 SpringBoot默认使用连接池HikariCP,不需要依赖. spring: datasource: driver-class-name: com.mysql.cj.j ...
- PHP集群session共享
集群的概念没有多复杂,其实就是多台电脑为了同一个目标在一起工作.在Web应用中,就是多个服务器提供一个站点的服务. 搭建PHP集群的第一步就是设置负载均衡. 默认情况下PHP是将session存在本地 ...
- 深入理解Spring Boot:Bean管理、原理解析与Maven高级应用
深入理解Spring Boot:Bean管理.原理解析与Maven高级应用 前言 大家好,今天我们来聊聊Spring Boot的核心内容,包括Bean管理.Spring Boot的工作原理以及Mave ...
- python获取引用对象的个数
python获取引用对象的个数 使用sys.getrefcount()来获取当前对象被引用了多少次,返回的结果比实际大1 import sys class A: pass a = A() #创建实例对 ...
- windows环境xampp搭建php电商项目/搭建禅道
windows环境xampp搭建php论坛/电商项目 一,首先下载xampp https://www.apachefriends.org/zh_cn/index.html 下载之后解压到E盘或者F盘的 ...