商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > ollama搭建本地ai大模型并应用调用的操作方法

ollama搭建本地ai大模型并应用调用的操作方法

  发布于2026-07-21 阅读(0)

扫一扫,手机访问

1、下载ollama

要搭建本地AI大模型,第一步自然是下载核心工具——Ollama。操作很简单:直接去官网,找到下载按钮,点击即可。下载完成后,像安装普通软件一样一路下一步就行。

2、启动配置模型

安装完成后,启动CMD窗口,输入以下命令就能拉取并运行模型:

ollama run llama3

如果想试试国产模型,用千问也是一样:

ollama run qwen2

模型下载完成后,直接在命令行输入问题,就能看到效果了。

ollama搭建本地ai大模型并应用调用的操作方法

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

注意,这个镜像文件比较大,下载需要耐心等待一会儿。安装完成后,在浏览器打开localhost:3000,就能看到漂亮的图形界面了。

ollama搭建本地ai大模型并应用调用的操作方法

4、搭建本地知识库

想让大模型更懂你的业务数据?那就需要搭建本地知识库了。这里推荐一个很实用的工具:AnythingLLM。它可以把你的文档、知识库整合进来,让模型基于私有数据回答问题。

5、配置文件

接下来是关键一步:开放11434端口,方便外部程序调用接口。如果涉及跨域访问,需要配置OLLAMA_ORIGINS=*。

Windows版

Windows用户直接在系统环境变量中配置即可。新建一个系统变量,变量名设为OLLAMA_HOST,变量值设为"0.0.0.0:11434"。

OLLAMA_HOST= "0.0.0.0:11434"

MAC版

Mac用户需要打开终端,执行以下命令:

sudo sh -c 'echo "export OLLAMA_HOST=0.0.0.0:11434">>/etc/profile'launchctl setenv OLLAMA_HOST "0.0.0.0:11434"

Linux版

Linux用户则需要在系统服务配置中设置:

Environment="OLLAMA\_HOST=0.0.0.0"

6、程序调用接口

环境配置好了,接下来看看怎么用程序调用。这里以Golang为例,介绍两种调用方式。

非流式响应

这种方式适合对实时性要求不高的场景,代码实现相对简单:

package mainimport ("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...)// 将请求体序列化为 JSONrequestBodyJSON, 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 olChatCompletionResponseerr = 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, // 假设用户的消息是第一个}) }}

流式响应

如果追求更快的响应速度和更好的用户体验,那么流式响应是更好的选择。它能让AI边生成边输出,不用等全部内容生成完才看到结果:

package mainimport (    "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 定义了请求体的结构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:   true,            //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        }               resutlmessage := ""        streamReader := resp.Body        buf := make([]byte, 1024) // 或者使用更大的缓冲区来提高读取性能        var completionResponse olChatCompletionResponse        fmt.Print("AI 回复:")        for {            n, err := streamReader.Read(buf)            if n > 0 {                // 处理接收到的数据,这里简单打印出来                //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, // 假设用户的消息是第一个        })    }}

以上就是完整的本地AI大模型搭建和调用流程。从下载Ollama、配置模型,到设置UI界面、搭建知识库,再到最后的程序接口调用,一步步操作下来,就能拥有一个完全本地化、可控的AI助手了。

本文转载于:https://www.jb51.net/program/330427d89.htm 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注