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

 更新时间:2024年11月11日 09:40:52   作者:小G同学  
这篇文章详细介绍了如何下载、安装和使用OLLAMA大模型,包括启动配置模型、配置UI界面、搭建本地知识库、配置文件开发、环境变量配置以及通过Golang实现接口调用的示例

1、下载ollama

1)https://ollama.com进入网址,点击download下载2)下载后直接安装即可。

2、启动配置模型

默认是启动cmd窗口直接输入

ollama run llama3

启动llama3大模型或者启动千问大模型

ollama run qwen2

启动输入你需要输入的问题即可

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即可打开网址

4、搭建本地知识库

AnythingLLM

5、配置文件

开发11434端口,便于外部访问接口,如果跨域访问的话配置OLLAMA_ORIGINS=*

Windows版

只需要在系统环境变量中直接配置,

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、程序调用接口

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例子:流式响应

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 定义了请求体的结构
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, // 假设用户的消息是第一个
        })
    }
}

到此这篇关于ollama搭建本地ai大模型并应用调用的操作方法的文章就介绍到这了,更多相关ollama搭建本地ai大模型内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • JetBrains Fleet 初体验

    JetBrains Fleet 初体验

    本文主要介绍了JetBrains Fleet 初体验,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-12-12
  • 让程序员都费解的10大编程语言特性

    让程序员都费解的10大编程语言特性

    这篇文章主要介绍了让程序员都费解的10大编程语言特性,本文罗列了如javascript、Ruby、Java等语言中让人费解的10个语言特性,需要的朋友可以参考下
    2014-09-09
  • 字符编码详解及由来(UNICODE,UTF-8,GBK) 比较详细

    字符编码详解及由来(UNICODE,UTF-8,GBK) 比较详细

    很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物。他们看到8个开关状态是好的,于是他们把这称为字节
    2012-04-04
  • APAP ALV进阶写法及优化详解

    APAP ALV进阶写法及优化详解

    这篇文章主要为大家介绍了APAP ALV进阶写法及优化详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • 在VS2019环境下使用Opencv调用GPU版本YOLOv4算法的详细过程

    在VS2019环境下使用Opencv调用GPU版本YOLOv4算法的详细过程

    随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了windows下YOLO的环境搭建流程,感兴趣的朋友跟随小编一起看看吧
    2022-10-10
  • AI经典书单 人工智能入门该读哪些书?

    AI经典书单 人工智能入门该读哪些书?

    学习人工智能该读哪些书可以快速入门呢?我的答案是多读经典书。方向对了即使慢点,总会走向成功的终点。而该读哪些书,小编推荐五份经典书单
    2017-11-11
  • 鸿蒙中Axios数据请求的封装和配置方法

    鸿蒙中Axios数据请求的封装和配置方法

    这篇文章主要介绍了鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2025-04-04
  • Web Jmeter–接口测试工具详解

    Web Jmeter–接口测试工具详解

    本文主要介绍Web Jmeter接口测试工具,这里整理了详细的资料来说明Jmeter 的使用,有需要的小伙伴可以参考下
    2016-09-09
  • Git分支管理策略

    Git分支管理策略

    这篇文章介绍了Git的分支管理策略,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • 基于DeepSeek-Coder的跨文件代码补全实战教程

    基于DeepSeek-Coder的跨文件代码补全实战教程

    本文介绍了DeepSeek-Coder33BInstruct版本在Python/Java/JavaScript等主流语言中的跨文件代码补全实战,感兴趣的朋友一起看看吧
    2025-02-02

最新评论