欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

ollama搭建本地ai大模型并應(yīng)用調(diào)用的操作方法

 更新時(shí)間:2024年11月11日 09:40:52   作者:小G同學(xué)  
這篇文章詳細(xì)介紹了如何下載、安裝和使用OLLAMA大模型,包括啟動(dòng)配置模型、配置UI界面、搭建本地知識(shí)庫(kù)、配置文件開發(fā)、環(huán)境變量配置以及通過Golang實(shí)現(xiàn)接口調(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)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Emscripten在Windows10下的安裝和配置

    Emscripten在Windows10下的安裝和配置

    這篇文章主要介紹了Emscripten在Windows10下的安裝和配置,Emscripten 是一個(gè)完整的 WebAssembly開源編譯器工具鏈,使用Emscripten可以參考平臺(tái)說明,感興趣的朋友一起看看吧
    2022-05-05
  • 最新IntelliJ IDEA 2020.2永久激活碼(親測(cè)有效)

    最新IntelliJ IDEA 2020.2永久激活碼(親測(cè)有效)

    今天一大波朋友反饋idea2020激活碼失效的問題,小編快馬加鞭給大家找到解決方案,本文以IDEA 2020.2.4激活碼破解教程為例給大家詳細(xì)介紹,需要idea2020激活碼的朋友快來參考下本文吧
    2020-11-11
  • OAuth 2.0授權(quán)協(xié)議詳解

    OAuth 2.0授權(quán)協(xié)議詳解

    這篇文章主要介紹了OAuth 2.0授權(quán)協(xié)議詳解,本文對(duì)OAuth協(xié)議做了詳解講解,對(duì)OAuth協(xié)議的各個(gè)方面做了分解,讀完本文你就會(huì)知道到底啥是OAuth了,需要的朋友可以參考下
    2014-09-09
  • 將新型冠狀病毒轉(zhuǎn)二進(jìn)制的代碼(首發(fā))

    將新型冠狀病毒轉(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ù)使用方法詳解

    鴻蒙系統(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
  • Postman使用詳解

    Postman使用詳解

    今天給大家介紹的這款網(wǎng)頁(yè)調(diào)試工具不僅可以調(diào)試簡(jiǎn)單的css、html、腳本等簡(jiǎn)單的網(wǎng)頁(yè)基本信息,它還可以發(fā)送幾乎所有類型的HTTP請(qǐng)求!Postman在發(fā)送網(wǎng)絡(luò)HTTP請(qǐng)求方面可以說是Chrome插件類產(chǎn)品中的代表產(chǎn)品之一
    2020-11-11
  • 通過lms.samples熟悉lms微服務(wù)框架的使用詳解

    通過lms.samples熟悉lms微服務(wù)框架的使用詳解

    這篇文章主要介紹了通過lms.samples熟悉lms微服務(wù)框架的使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • TypeScript類型檢查詳談及火爆原因

    TypeScript類型檢查詳談及火爆原因

    這篇文章主要為大家介紹了TypeScript類型檢查以及火爆原因,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 圖文解析布隆過濾器大小的算法公式

    圖文解析布隆過濾器大小的算法公式

    這篇文章主要為大家介紹了布隆過濾器大小的算法公式圖文詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪<BR>
    2022-04-04
  • 簡(jiǎn)單實(shí)用的aixcoder智能編程助手開發(fā)插件推薦

    簡(jiǎn)單實(shí)用的aixcoder智能編程助手開發(fā)插件推薦

    本文給大家分享一款簡(jiǎn)單實(shí)用的aixcoder智能編程助手開發(fā)插件推薦 ,需要的朋友可以參考下
    2019-06-06

最新評(píng)論