ollama搭建本地ai大模型并應(yīng)用調(diào)用的操作方法
1、下載ollama
1)https://ollama.com進(jìn)入網(wǎng)址,點(diǎn)擊download下載2)下載后直接安裝即可。
2、啟動(dòng)配置模型
默認(rèn)是啟動(dòng)cmd窗口直接輸入
ollama run llama3
啟動(dòng)llama3大模型或者啟動(dòng)千問大模型
ollama run qwen2
啟動(dòng)輸入你需要輸入的問題即可
3、配置UI界面
安裝docker并部署web操作界面
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
安裝完畢后,安裝包較大,需等待一段時(shí)間。localhost:3000即可打開網(wǎng)址
4、搭建本地知識(shí)庫(kù)
AnythingLLM
5、配置文件
開發(fā)11434端口,便于外部訪問接口,如果跨域訪問的話配置OLLAMA_ORIGINS=*
Windows版
只需要在系統(tǒng)環(huán)境變量中直接配置,
OLLAMA_HOST為變量名,"0.0.0.0:11434"為變量值
OLLAMA_HOST= "0.0.0.0:11434"
MAC版
配置OLLAMA_HOST
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
Environment="OLLAMA\_HOST=0.0.0.0"
6、程序調(diào)用接口
golang實(shí)現(xiàn)例子:流式響應(yīng)速度更快,用戶體驗(yàn)更佳。
golang例子:非流式響應(yīng)
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 定義了請(qǐng)求體的結(jié)構(gòu) 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 定義了響應(yīng)體的結(jié)構(gòu) type olChatCompletionResponse struct { //Choices []struct { Message struct { Role string `json:"role"` Content string `json:"content"` } `json:"message"` //} `json:"choices"` } // sendRequestWithRetry 發(fā)送請(qǐng)求并處理可能的429錯(cuò)誤 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) // 默認(rèn)等待5秒 } return olsendRequestWithRetry(client, requestBody) // 遞歸重試 } return resp, nil } func main() { client := &http.Client{} // 創(chuàng)建一個(gè)全局的 HTTP 客戶端實(shí)例 // 初始化對(duì)話歷史記錄 history := []struct { Role string `json:"role"` Content string `json:"content"` }{ {"system", "你是一位唐代詩(shī)人,特別擅長(zhǎng)模仿李白的風(fēng)格。"}, } // 創(chuàng)建標(biāo)準(zhǔn)輸入的掃描器 scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("請(qǐng)輸入您的問題(或者輸入 '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, }) // 創(chuàng)建請(qǐng)求體 requestBody := olChatCompletionRequest{ Model: omodelID, Messages: history, Stream: false, //Temperature: 0.7, } // 構(gòu)建完整的請(qǐng)求體,包含歷史消息 requestBody.Messages = append([]struct { Role string `json:"role"` Content string `json:"content"` }{ { Role: "system", Content: "你是一位唐代詩(shī)人,特別擅長(zhǎng)模仿李白的風(fēng)格。", }, }, history...) // 將請(qǐng)求體序列化為 JSON requestBodyJSON, err := json.Marshal(requestBody) if err != nil { fmt.Println("Error marshalling request body:", err) continue } fmt.Println("wocao:" + string(requestBodyJSON)) // 發(fā)送請(qǐng)求并處理重試 resp, err := olsendRequestWithRetry(client, requestBodyJSON) if err != nil { fmt.Println("Error sending request after retries:", err) continue } defer resp.Body.Close() // 檢查響應(yīng)狀態(tài)碼 if resp.StatusCode != http.StatusOK { fmt.Printf("Received non-200 response status code: %d\n", resp.StatusCode) continue } // 讀取響應(yīng)體 responseBody, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response body:", err) continue } //fmt.Println("0000" + string(responseBody)) // 解析響應(yīng)體 var completionResponse olChatCompletionResponse err = json.Unmarshal(responseBody, &completionResponse) if err != nil { fmt.Println("Error unmarshalling response body:", err) continue } fmt.Printf("AI 回復(fù): %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, // 假設(shè)用戶的消息是第一個(gè) }) } }
golang例子:流式響應(yīng)
package main import ( "bufio" "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "time" ) const ( obaseURL = "http://localhost:11434/api" omodelID = "qwen2:0.5b" // 選擇合適的模型 oendpoint = "/chat" //"/chat/completions" ) // ChatCompletionRequest 定義了請(qǐng)求體的結(jié)構(gòu) 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 定義了響應(yīng)體的結(jié)構(gòu) type olChatCompletionResponse struct { //Choices []struct { Message struct { Role string `json:"role"` Content string `json:"content"` } `json:"message"` //} `json:"choices"` } // sendRequestWithRetry 發(fā)送請(qǐng)求并處理可能的429錯(cuò)誤 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) // 默認(rèn)等待5秒 } return olsendRequestWithRetry(client, requestBody) // 遞歸重試 } return resp, nil } func main() { client := &http.Client{} // 創(chuàng)建一個(gè)全局的 HTTP 客戶端實(shí)例 // 初始化對(duì)話歷史記錄 history := []struct { Role string `json:"role"` Content string `json:"content"` }{ {"system", "你是一位唐代詩(shī)人,特別擅長(zhǎng)模仿李白的風(fēng)格。"}, } // 創(chuàng)建標(biāo)準(zhǔn)輸入的掃描器 scanner := bufio.NewScanner(os.Stdin) for { fmt.Print("請(qǐng)輸入您的問題(或者輸入 '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, }) // 創(chuàng)建請(qǐng)求體 requestBody := olChatCompletionRequest{ Model: omodelID, Messages: history, Stream: true, //Temperature: 0.7, } // 構(gòu)建完整的請(qǐng)求體,包含歷史消息 requestBody.Messages = append([]struct { Role string `json:"role"` Content string `json:"content"` }{ { Role: "system", Content: "你是一位唐代詩(shī)人,特別擅長(zhǎng)模仿李白的風(fēng)格。", }, }, history...) // 將請(qǐng)求體序列化為 JSON requestBodyJSON, err := json.Marshal(requestBody) if err != nil { fmt.Println("Error marshalling request body:", err) continue } fmt.Println("wocao:" + string(requestBodyJSON)) // 發(fā)送請(qǐng)求并處理重試 resp, err := olsendRequestWithRetry(client, requestBodyJSON) if err != nil { fmt.Println("Error sending request after retries:", err) continue } defer resp.Body.Close() // 檢查響應(yīng)狀態(tài)碼 if resp.StatusCode != http.StatusOK { fmt.Printf("Received non-200 response status code: %d\n", resp.StatusCode) continue } resutlmessage := "" streamReader := resp.Body buf := make([]byte, 1024) // 或者使用更大的緩沖區(qū)來提高讀取性能 var completionResponse olChatCompletionResponse fmt.Print("AI 回復(fù):") for { n, err := streamReader.Read(buf) if n > 0 { // 處理接收到的數(shù)據(jù),這里簡(jiǎn)單打印出來 //fmt.Print(string(buf[:n])) err = json.Unmarshal(buf[:n], &completionResponse) fmt.Print(string(completionResponse.Message.Content)) resutlmessage+=string(completionResponse.Message.Content) if err != nil { fmt.Println("Error unmarshalling response body:", err) continue } } if err != nil { if err == io.EOF { fmt.Println("") break } panic(err) } } // 將用戶的消息添加到歷史記錄中 history = append(history, struct { Role string `json:"role"` Content string `json:"content"` }{ Role: completionResponse.Message.Role, Content: resutlmessage,//completionResponse.Message.Content, // 假設(shè)用戶的消息是第一個(gè) }) } }
到此這篇關(guān)于ollama搭建本地ai大模型并應(yīng)用調(diào)用的操作方法的文章就介紹到這了,更多相關(guān)ollama搭建本地ai大模型內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 大語(yǔ)言模型的開發(fā)利器langchainan安裝使用快速入門學(xué)習(xí)
- langchain Prompt大語(yǔ)言模型使用技巧詳解
- Docker?AIGC等大模型深度學(xué)習(xí)環(huán)境搭建步驟最新詳細(xì)版
- 前端AI機(jī)器學(xué)習(xí)在瀏覽器中訓(xùn)練模型
- AI:如何訓(xùn)練機(jī)器學(xué)習(xí)的模型
- django數(shù)據(jù)模型on_delete, db_constraint的使用詳解
- TensorFlow入門使用 tf.train.Saver()保存模型
- Python從零開始訓(xùn)練AI模型的實(shí)用教程
相關(guān)文章
最新IntelliJ IDEA 2020.2永久激活碼(親測(cè)有效)
今天一大波朋友反饋idea2020激活碼失效的問題,小編快馬加鞭給大家找到解決方案,本文以IDEA 2020.2.4激活碼破解教程為例給大家詳細(xì)介紹,需要idea2020激活碼的朋友快來參考下本文吧2020-11-11將新型冠狀病毒轉(zhuǎn)二進(jìn)制的代碼(首發(fā))
這篇文章主要介紹了新型冠狀病毒轉(zhuǎn)二進(jìn)制的相關(guān)知識(shí),分為java,js,php,pthon等語(yǔ)言的實(shí)例代碼,需要的朋友可以參考下2020-02-02鴻蒙系統(tǒng)中的Webview技術(shù)使用方法詳解
webView類是View類的一個(gè)擴(kuò)展,用來顯示網(wǎng)頁(yè),它不包含任何的網(wǎng)頁(yè)瀏覽器的特征,像沒有導(dǎo)航控制和地址欄,使用起來也很方便,這篇文章主要給大家介紹了關(guān)于鴻蒙系統(tǒng)中Webview技術(shù)使用的相關(guān)資料,需要的朋友可以參考下2024-07-07通過lms.samples熟悉lms微服務(wù)框架的使用詳解
這篇文章主要介紹了通過lms.samples熟悉lms微服務(wù)框架的使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04簡(jiǎn)單實(shí)用的aixcoder智能編程助手開發(fā)插件推薦
本文給大家分享一款簡(jiǎn)單實(shí)用的aixcoder智能編程助手開發(fā)插件推薦 ,需要的朋友可以參考下2019-06-06