最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)境變量配置以及通過(guò)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)千問(wèn)大模型

ollama run qwen2

啟動(dòng)輸入你需要輸入的問(wèn)題即可

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端口,便于外部訪問(wèn)接口,如果跨域訪問(wèn)的話配置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)輸入您的問(wèn)題(或者輸入 '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)輸入您的問(wèn)題(或者輸入 '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ū)來(lái)提高讀取性能
        var completionResponse olChatCompletionResponse
        fmt.Print("AI 回復(fù):")
        for {
            n, err := streamReader.Read(buf)
            if n > 0 {
                // 處理接收到的數(shù)據(jù),這里簡(jiǎn)單打印出來(lái)
                //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)文章

  • JetBrains Fleet 初體驗(yàn)

    JetBrains Fleet 初體驗(yàn)

    本文主要介紹了JetBrains Fleet 初體驗(yàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • 讓程序員都費(fèi)解的10大編程語(yǔ)言特性

    讓程序員都費(fèi)解的10大編程語(yǔ)言特性

    這篇文章主要介紹了讓程序員都費(fèi)解的10大編程語(yǔ)言特性,本文羅列了如javascript、Ruby、Java等語(yǔ)言中讓人費(fèi)解的10個(gè)語(yǔ)言特性,需要的朋友可以參考下
    2014-09-09
  • 字符編碼詳解及由來(lái)(UNICODE,UTF-8,GBK) 比較詳細(xì)

    字符編碼詳解及由來(lái)(UNICODE,UTF-8,GBK) 比較詳細(xì)

    很久很久以前,有一群人,他們決定用8個(gè)可以開合的晶體管來(lái)組合成不同的狀態(tài),以表示世界上的萬(wàn)物。他們看到8個(gè)開關(guān)狀態(tài)是好的,于是他們把這稱為字節(jié)
    2012-04-04
  • APAP?ALV進(jìn)階寫法及優(yōu)化詳解

    APAP?ALV進(jìn)階寫法及優(yōu)化詳解

    這篇文章主要為大家介紹了APAP?ALV進(jìn)階寫法及優(yōu)化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • 在VS2019環(huán)境下使用Opencv調(diào)用GPU版本YOLOv4算法的詳細(xì)過(guò)程

    在VS2019環(huán)境下使用Opencv調(diào)用GPU版本YOLOv4算法的詳細(xì)過(guò)程

    隨著人工智能的不斷發(fā)展,機(jī)器學(xué)習(xí)這門技術(shù)也越來(lái)越重要,很多人都開啟了學(xué)習(xí)機(jī)器學(xué)習(xí),本文就介紹了windows下YOLO的環(huán)境搭建流程,感興趣的朋友跟隨小編一起看看吧
    2022-10-10
  • AI經(jīng)典書單 人工智能入門該讀哪些書?

    AI經(jīng)典書單 人工智能入門該讀哪些書?

    學(xué)習(xí)人工智能該讀哪些書可以快速入門呢?我的答案是多讀經(jīng)典書。方向?qū)α思词孤c(diǎn),總會(huì)走向成功的終點(diǎn)。而該讀哪些書,小編推薦五份經(jīng)典書單
    2017-11-11
  • 鴻蒙中Axios數(shù)據(jù)請(qǐng)求的封裝和配置方法

    鴻蒙中Axios數(shù)據(jù)請(qǐng)求的封裝和配置方法

    這篇文章主要介紹了鴻蒙中Axios數(shù)據(jù)請(qǐng)求的封裝和配置方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2025-04-04
  • Web Jmeter–接口測(cè)試工具詳解

    Web Jmeter–接口測(cè)試工具詳解

    本文主要介紹Web Jmeter接口測(cè)試工具,這里整理了詳細(xì)的資料來(lái)說(shuō)明Jmeter 的使用,有需要的小伙伴可以參考下
    2016-09-09
  • Git分支管理策略

    Git分支管理策略

    這篇文章介紹了Git的分支管理策略,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03
  • 基于DeepSeek-Coder的跨文件代碼補(bǔ)全實(shí)戰(zhàn)教程

    基于DeepSeek-Coder的跨文件代碼補(bǔ)全實(shí)戰(zhàn)教程

    本文介紹了DeepSeek-Coder33BInstruct版本在Python/Java/JavaScript等主流語(yǔ)言中的跨文件代碼補(bǔ)全實(shí)戰(zhàn),感興趣的朋友一起看看吧
    2025-02-02

最新評(píng)論

勃利县| 百色市| 绥宁县| 平乡县| 高平市| 澄城县| 大姚县| 忻州市| 教育| 武清区| 渭源县| 南丹县| 芜湖市| 松原市| 两当县| 清流县| 慈溪市| 河东区| 巨野县| 新营市| 无为县| 阿拉善左旗| 鲁山县| 迁西县| 崇仁县| 阜平县| 靖安县| 土默特左旗| 黎城县| 合肥市| 额敏县| 乌拉特中旗| 红原县| 霍城县| 五寨县| 兰西县| 揭西县| 平遥县| 四平市| 无锡市| 沭阳县|