快速入门:使用Ollama的LangChainGo
通过运行第一个程序来开始使用LangChainGo和Ollama。Ollama为所有计算机平台提供了最简单的方法来进行本地LLM推理。
先决条件
- Ollama:下载并安装Ollama
- Go:下载并安装Go
设置
Ollama在您的机器上本地运行,不需要API密钥。但是您需要安装好Ollama并且下载一个模型。
安装Ollama
请按照ollama.ai上的说明为您的操作系统进行安装。
下载模型
在运行示例之前,请先下载一个模型。该示例使用llama2
模型:
ollama pull llama2
步骤
- 初始化Ollama:在终端中执行命令
ollama run llama2
。首次运行可能需要一些时间,因为模型需要被拉取到您的计算机上。 - 运行示例:输入以下命令:
go run github.com/tmc/langchaingo/examples/ollama-completion-example@main
您应该会看到类似如下的输出:
首次踏上月球的人是美国宇航员尼尔·阿姆斯特朗,他在1969年7月20日的阿波罗11号任务中踏上了月球表面。
恭喜!您已经成功构建并执行了第一个基于开源LLM的本地推理程序。
以下是整个程序(来自ollama-completion-example):
package main
import (
"context"
"fmt"
"log"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/ollama"
)
func main() {
llm, err := ollama.New(ollama.WithModel("llama2"))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
completion, err := llms.GenerateFromSinglePrompt(
ctx,
llm,
"Human: Who was the first man to walk on the moon?\nAssistant:",
llms.WithTemperature(0.8),
llms.WithStreamingFunc(func(ctx context.Context, chunk []byte) error {
fmt.Print(string(chunk))
return nil
}),
)
if err != nil {
log.Fatal(err)
}
_ = completion
}